blob: ac3550408cfa0fcf160ea893b028dfde7f6a5be9 [file] [log] [blame]
Emeric Vigier2f625822012-08-06 11:09:52 -04001#include <cc++/thread.h>
2#include <cstdio>
3
4#ifdef CCXX_NAMESPACES
5using namespace ost;
6#endif
7
8// This is a little regression test
9//
10
11class ThreadTest: public Thread
12{
13public:
14 ThreadTest();
15 void run();
16};
17
18volatile int n = 0;
19
20bool WaitNValue(int value)
21{
22 for(int i=0;; ++i) {
23 if (n == value)
24 break;
25 if (i >= 100)
26 return false;
27 Thread::sleep(10);
28 }
29 return true;
30}
31
32bool WaitChangeNValue(int value)
33{
34 for(int i=0;; ++i) {
35 if (n != value)
36 break;
37 if (i >= 100)
38 return false;
39 Thread::sleep(10);
40 }
41 return true;
42}
43
44ThreadTest::ThreadTest()
45{
46}
47
48void ThreadTest::run()
49{
50 setCancel(Thread::cancelDeferred);
51 n = 1;
52
53 // wait for main thread
54 if (!WaitNValue(2)) return;
55
56 // increment infinitely
57 for(;;) {
58 yield();
59 n = n+1;
60 }
61}
62
63bool TestChange(bool shouldChange)
64{
65 if (shouldChange)
66 printf("- thread should change n...");
67 else
68 printf("- thread should not change n...");
69 if (WaitChangeNValue(n) == shouldChange) {
70 printf("ok\n");
71 return true;
72 }
73 printf("ko\n");
74 return false;
75}
76
77#undef ERROR
78#undef OK
79#define ERROR {printf("ko\n"); return 1; }
80#define OK {printf("ok\n"); }
81
82#define TEST_CHANGE(b) if (!TestChange(b)) return 1;
83
84int main(int argc, char* argv[])
85{
86 ThreadTest test;
87
88 // test only thread, without sincronization
89 printf("***********************************************\n");
90 printf("* Testing class Thread without syncronization *\n");
91 printf("***********************************************\n");
92
93 printf("Testing thread creation\n\n");
94 n = 0;
95 test.start();
96
97 // wait for n == 1
98 printf("- thread should set n to 1...");
99 if (WaitNValue(1)) OK
100 else ERROR;
101
102 // increment number in thread
103 printf("\nTesting thread is working\n\n");
104 n = 2;
105 TEST_CHANGE(true);
106 TEST_CHANGE(true);
107
108 // suspend thread, variable should not change
109 printf("\nTesting suspend & resume\n\n");
110 test.suspend();
111 TEST_CHANGE(false);
112 TEST_CHANGE(false);
113
114 // resume, variable should change
115 test.resume();
116 TEST_CHANGE(true);
117 TEST_CHANGE(true);
118
119 printf("\nTesting recursive suspend & resume\n\n");
120 test.suspend();
121 test.suspend();
122 TEST_CHANGE(false);
123 TEST_CHANGE(false);
124
125 test.resume();
126 TEST_CHANGE(false);
127 TEST_CHANGE(false);
128 test.resume();
129 TEST_CHANGE(true);
130 TEST_CHANGE(true);
131
132 printf("\nTesting no suspend on resume\n\n");
133 test.resume();
134 TEST_CHANGE(true);
135 TEST_CHANGE(true);
136
137 // suspend thread, variable should not change
138 printf("\nTesting resuspend\n\n");
139 test.suspend();
140 TEST_CHANGE(false);
141 TEST_CHANGE(false);
142
143 printf("\nNow program should finish... :)\n");
144 test.resume();
145
146 return 0;
147}