-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPreThread.cpp
More file actions
75 lines (68 loc) · 1.5 KB
/
PreThread.cpp
File metadata and controls
75 lines (68 loc) · 1.5 KB
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
#include "PreThread.h"
void* PreThread_func( void* arg ) {
PreThread* p = (PreThread*)arg;
return p->func();
}
void* PreThread::func() {
pthread_mutex_lock( &mut );
while ( 1 ) {
pthread_cond_wait( &start, &mut );
if ( foo == PreThread_func ) {
// this is the signal to quit
break;
}
if ( foo != NULL ) {
pthread_mutex_unlock( &mut );
retval = foo( arg );
pthread_mutex_lock( &mut );
foo = NULL;
pthread_cond_broadcast( &stop );
}
}
pthread_mutex_unlock( &mut );
return NULL;
}
PreThread::PreThread() {
pthread_mutex_init( &mut, NULL );
pthread_cond_init( &start, NULL );
pthread_cond_init( &stop, NULL );
foo = NULL;
arg = NULL;
retval = NULL;
pthread_create( &thread, NULL, PreThread_func, this );
}
PreThread::~PreThread() {
run( PreThread_func, NULL );
pthread_join( thread, NULL );
pthread_mutex_destroy( &mut );
pthread_cond_destroy( &start );
pthread_cond_destroy( &stop );
}
bool PreThread::busy() {
bool toret;
pthread_mutex_lock( &mut );
toret = (foo != NULL);
pthread_mutex_unlock( &mut );
return toret;
}
int PreThread::run( void* (*fooIn)(void*), void* argIn ) {
pthread_mutex_lock( &mut );
while ( foo != NULL ) {
pthread_cond_wait( &stop, &mut );
}
foo = fooIn;
arg = argIn;
pthread_cond_signal( &start );
pthread_mutex_unlock( &mut );
return 0;
}
void* PreThread::join() {
void* toret;
pthread_mutex_lock( &mut );
while ( foo != NULL ) {
pthread_cond_wait( &stop, &mut );
}
toret = retval;
pthread_mutex_unlock( &mut );
return toret;
}