Skip to content

Commit 05c688b

Browse files
authored
Merge 178671a into 17486fd
2 parents 17486fd + 178671a commit 05c688b

File tree

1 file changed

+9
-5
lines changed

1 file changed

+9
-5
lines changed

examples/cpp-multithread/main.cpp

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,15 @@
66
#include <string.h>
77
#include <stdlib.h>
88
#include <time.h>
9+
#include <atomic>
910
#include "../../ui.h"
1011
using namespace std;
1112

1213
uiMultilineEntry *e;
1314
condition_variable cv;
1415
mutex m;
15-
unique_lock<mutex> ourlock(m);
1616
thread *timeThread;
17+
atomic<bool> running(true);
1718

1819
void sayTime(void *data)
1920
{
@@ -25,8 +26,9 @@ void sayTime(void *data)
2526

2627
void threadproc(void)
2728
{
28-
ourlock.lock();
29-
while (cv.wait_for(ourlock, chrono::seconds(1)) == cv_status::timeout) {
29+
unique_lock<mutex> ourlock(m);
30+
while (running.load()) {
31+
cv.wait_for(ourlock, chrono::seconds(1));
3032
time_t t;
3133
char *base;
3234
char *s;
@@ -41,6 +43,10 @@ void threadproc(void)
4143

4244
int onClosing(uiWindow *w, void *data)
4345
{
46+
{
47+
unique_lock<mutex> l(m);
48+
running = false;
49+
}
4450
cv.notify_all();
4551
// C++ throws a hissy fit if you don't do this
4652
// we might as well, to ensure no uiQueueMain() gets in after uiQuit()
@@ -81,8 +87,6 @@ int main(void)
8187

8288
uiBoxAppend(b, uiControl(e), 1);
8389

84-
// timeThread needs to lock ourlock itself - see http://stackoverflow.com/a/34121629/3408572
85-
ourlock.unlock();
8690
timeThread = new thread(threadproc);
8791

8892
uiWindowOnClosing(w, onClosing, NULL);

0 commit comments

Comments
 (0)