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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
|
#include <cc++/thread.h>
#include <cstdio>
#ifdef CCXX_NAMESPACES
using namespace ost;
#endif
// This is a little regression test
//
class ThreadTest: public Thread
{
public:
ThreadTest();
void run();
};
volatile int n = 0;
bool WaitNValue(int value)
{
for(int i=0;; ++i) {
if (n == value)
break;
if (i >= 100)
return false;
Thread::sleep(10);
}
return true;
}
bool WaitChangeNValue(int value)
{
for(int i=0;; ++i) {
if (n != value)
break;
if (i >= 100)
return false;
Thread::sleep(10);
}
return true;
}
ThreadTest::ThreadTest()
{
}
void ThreadTest::run()
{
setCancel(Thread::cancelDeferred);
n = 1;
// wait for main thread
if (!WaitNValue(2)) return;
// increment infinitely
for(;;) {
yield();
n = n+1;
}
}
bool TestChange(bool shouldChange)
{
if (shouldChange)
printf("- thread should change n...");
else
printf("- thread should not change n...");
if (WaitChangeNValue(n) == shouldChange) {
printf("ok\n");
return true;
}
printf("ko\n");
return false;
}
#undef ERROR
#undef OK
#define ERROR {printf("ko\n"); return 1; }
#define OK {printf("ok\n"); }
#define TEST_CHANGE(b) if (!TestChange(b)) return 1;
int main(int argc, char* argv[])
{
ThreadTest test;
// test only thread, without sincronization
printf("***********************************************\n");
printf("* Testing class Thread without syncronization *\n");
printf("***********************************************\n");
printf("Testing thread creation\n\n");
n = 0;
test.start();
// wait for n == 1
printf("- thread should set n to 1...");
if (WaitNValue(1)) OK
else ERROR;
// increment number in thread
printf("\nTesting thread is working\n\n");
n = 2;
TEST_CHANGE(true);
TEST_CHANGE(true);
// suspend thread, variable should not change
printf("\nTesting suspend & resume\n\n");
test.suspend();
TEST_CHANGE(false);
TEST_CHANGE(false);
// resume, variable should change
test.resume();
TEST_CHANGE(true);
TEST_CHANGE(true);
printf("\nTesting recursive suspend & resume\n\n");
test.suspend();
test.suspend();
TEST_CHANGE(false);
TEST_CHANGE(false);
test.resume();
TEST_CHANGE(false);
TEST_CHANGE(false);
test.resume();
TEST_CHANGE(true);
TEST_CHANGE(true);
printf("\nTesting no suspend on resume\n\n");
test.resume();
TEST_CHANGE(true);
TEST_CHANGE(true);
// suspend thread, variable should not change
printf("\nTesting resuspend\n\n");
test.suspend();
TEST_CHANGE(false);
TEST_CHANGE(false);
printf("\nNow program should finish... :)\n");
test.resume();
return 0;
}
|