wibble 1.1
thread.test.h
Go to the documentation of this file.
1/* -*- C++ -*- (c) 2007 Petr Rockai <me@mornfall.net>
2 (c) 2007 Enrico Zini <enrico@enricozini.org> */
3
4#include <wibble/sys/mutex.h>
5#include <wibble/sys/thread.h>
6
7#include <wibble/test.h>
8
9using namespace std;
10using namespace wibble::sys;
11
12struct TestThread {
13
14 // Test threads that just assigns a value to an int and exists
15 class Thread1 : public Thread
16 {
17 protected:
18 int& res;
19 int val;
20
21 void* main()
22 {
23 res = val;
24 return reinterpret_cast<void*>(val);
25 }
26 public:
27 Thread1(int& res, int val) : res(res), val(val) {}
28 };
29
30 // Thread that continuously increments an int value
31 class Thread2 : public Thread
32 {
33 protected:
34 int& res;
36 bool done;
37
38 void* main()
39 {
40 while (!done)
41 {
42 MutexLock lock(mutex);
43 ++res;
44 }
45 return 0;
46 }
47
48 public:
50 res(res), mutex(mutex), done(false) {}
51 void quit() { done = true; }
52 };
53
54 // Test that threads are executed
56 int val = 0;
57
58 Thread1 assigner(val, 42);
59 assigner.start();
60 assert_eq(assigner.join(), reinterpret_cast<void*>(42));
61 assert_eq(val, 42);
62 }
63
64 // Use mutexes to access shared memory
66 int val = 0;
67 Mutex mutex;
68
69 Thread2 incrementer(val, mutex);
70 incrementer.start();
71
72 bool done = false;
73 while (!done)
74 {
75 MutexLock lock(mutex);
76 if (val > 100)
77 done = true;
78 }
79 incrementer.quit();
80 assert_eq(incrementer.join(), static_cast<void*>(0));
81 }
82
83};
84
85// vim:set ts=4 sw=4:
Definition thread.test.h:16
Thread1(int &res, int val)
Definition thread.test.h:27
int & res
Definition thread.test.h:18
int val
Definition thread.test.h:19
void * main()
Main thread function, executed in the new thread after creation.
Definition thread.test.h:21
Definition thread.test.h:32
int & res
Definition thread.test.h:34
Thread2(int &res, Mutex &mutex)
Definition thread.test.h:49
bool done
Definition thread.test.h:36
void * main()
Main thread function, executed in the new thread after creation.
Definition thread.test.h:38
Mutex & mutex
Definition thread.test.h:35
void quit()
Definition thread.test.h:51
pthread mutex wrapper; WARNING: the class allows copying and assignment, but this is not always safe.
Definition mutex.h:48
Encapsulates a thread.
Definition thread.h:84
Definition buffer.cpp:28
Definition thread.test.h:12
Test execution()
Definition thread.test.h:55
Test sharedMemory()
Definition thread.test.h:65
Definition amorph.h:30
#define assert_eq(x, y)
Definition test.h:33