wibble
1.1
Main Page
Namespaces
Classes
Files
File List
File Members
wibble
sys
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
9
using namespace
std;
10
using namespace
wibble::sys;
11
12
struct
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
;
35
Mutex
&
mutex
;
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
:
49
Thread2
(
int
& res,
Mutex
& mutex) :
50
res(res), mutex(mutex), done(false) {}
51
void
quit
() { done =
true
; }
52
};
53
54
// Test that threads are executed
55
Test
execution
() {
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
65
Test
sharedMemory
() {
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:
Generated on Wed Oct 23 2013 17:14:25 for wibble by
1.8.4