From 4b20c5b045bfb21fef8a9ea2f0e6ece1eb84ef58 Mon Sep 17 00:00:00 2001 From: Mariusz Kasolik Date: Mon, 29 Oct 2018 06:48:54 +0100 Subject: [PATCH 1/2] examples/cpp-multithreaded: fixed locks and timeThread terminate conditions C++ unique_lock created through constructor with an argument creates already locked lock. The lock is unlocked with destructor. condition_variable::wait_for returns true when await at least specified timeout false otherwise. There is no guarantee that it returns false when notified, therefore thread exit is done through extra flag 'running'. --- examples/cpp-multithread/main.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/examples/cpp-multithread/main.cpp b/examples/cpp-multithread/main.cpp index f97bc6f2a..02450b3e1 100644 --- a/examples/cpp-multithread/main.cpp +++ b/examples/cpp-multithread/main.cpp @@ -12,8 +12,8 @@ using namespace std; uiMultilineEntry *e; condition_variable cv; mutex m; -unique_lock ourlock(m); thread *timeThread; +volatile bool running = true; void sayTime(void *data) { @@ -25,8 +25,9 @@ void sayTime(void *data) void threadproc(void) { - ourlock.lock(); - while (cv.wait_for(ourlock, chrono::seconds(1)) == cv_status::timeout) { + unique_lock ourlock(m); + while (running) { + cv.wait_for(ourlock, chrono::seconds(1)); time_t t; char *base; char *s; @@ -41,6 +42,10 @@ void threadproc(void) int onClosing(uiWindow *w, void *data) { + { + unique_lock l(m); + running = false; + } cv.notify_all(); // C++ throws a hissy fit if you don't do this // we might as well, to ensure no uiQueueMain() gets in after uiQuit() @@ -81,8 +86,6 @@ int main(void) uiBoxAppend(b, uiControl(e), 1); - // timeThread needs to lock ourlock itself - see http://stackoverflow.com/a/34121629/3408572 - ourlock.unlock(); timeThread = new thread(threadproc); uiWindowOnClosing(w, onClosing, NULL); From 178671a7bd844cef53d202b7ab39aa02211e11e0 Mon Sep 17 00:00:00 2001 From: Mariusz Kasolik Date: Fri, 31 May 2019 14:27:09 +0200 Subject: [PATCH 2/2] examples/cpp-multithreaded: running flag is atomic --- examples/cpp-multithread/main.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/examples/cpp-multithread/main.cpp b/examples/cpp-multithread/main.cpp index 02450b3e1..ed65535fa 100644 --- a/examples/cpp-multithread/main.cpp +++ b/examples/cpp-multithread/main.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include "../../ui.h" using namespace std; @@ -13,7 +14,7 @@ uiMultilineEntry *e; condition_variable cv; mutex m; thread *timeThread; -volatile bool running = true; +atomic running(true); void sayTime(void *data) { @@ -26,7 +27,7 @@ void sayTime(void *data) void threadproc(void) { unique_lock ourlock(m); - while (running) { + while (running.load()) { cv.wait_for(ourlock, chrono::seconds(1)); time_t t; char *base;