aboutsummaryrefslogtreecommitdiff
path: root/src/libui_sdl/libui/examples/cpp-multithread/main.cpp
blob: f97bc6f2a229ddbcdf28fce3e499858cd841b267 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// 6 december 2015
#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "../../ui.h"
using namespace std;

uiMultilineEntry *e;
condition_variable cv;
mutex m;
unique_lock<mutex> ourlock(m);
thread *timeThread;

void sayTime(void *data)
{
	char *s = (char *) data;

	uiMultilineEntryAppend(e, s);
	delete s;
}

void threadproc(void)
{
	ourlock.lock();
	while (cv.wait_for(ourlock, chrono::seconds(1)) == cv_status::timeout) {
		time_t t;
		char *base;
		char *s;

		t = time(NULL);
		base = ctime(&t);
		s = new char[strlen(base) + 1];
		strcpy(s, base);
		uiQueueMain(sayTime, s);
	}
}

int onClosing(uiWindow *w, void *data)
{
	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()
	timeThread->join();
	uiQuit();
	return 1;
}

void saySomething(uiButton *b, void *data)
{
	uiMultilineEntryAppend(e, "Saying something\n");
}

int main(void)
{
	uiInitOptions o;
	uiWindow *w;
	uiBox *b;
	uiButton *btn;

	memset(&o, 0, sizeof (uiInitOptions));
	if (uiInit(&o) != NULL)
		abort();

	w = uiNewWindow("Hello", 320, 240, 0);
	uiWindowSetMargined(w, 1);

	b = uiNewVerticalBox();
	uiBoxSetPadded(b, 1);
	uiWindowSetChild(w, uiControl(b));

	e = uiNewMultilineEntry();
	uiMultilineEntrySetReadOnly(e, 1);

	btn = uiNewButton("Say Something");
	uiButtonOnClicked(btn, saySomething, NULL);
	uiBoxAppend(b, uiControl(btn), 0);

	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);
	uiControlShow(uiControl(w));
	uiMain();
	return 0;
}