spthread.cpp
2.4 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
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
#include "spthread.hpp"
#ifdef WIN32
int sp_thread_mutex_init( sp_thread_mutex_t * mutex, void * attr )
{
*mutex = CreateMutex( NULL, FALSE, NULL );
return NULL == * mutex ? GetLastError() : 0;
}
int sp_thread_mutex_destroy( sp_thread_mutex_t * mutex )
{
int ret = CloseHandle( *mutex );
return 0 == ret ? GetLastError() : 0;
}
int sp_thread_mutex_lock( sp_thread_mutex_t * mutex )
{
int ret = WaitForSingleObject( *mutex, INFINITE );
return WAIT_OBJECT_0 == ret ? 0 : GetLastError();
}
int sp_thread_mutex_unlock( sp_thread_mutex_t * mutex )
{
int ret = ReleaseMutex( *mutex );
return 0 != ret ? 0 : GetLastError();
}
int sp_thread_cond_init( sp_thread_cond_t * cond, void * attr )
{
*cond = CreateEvent( NULL, FALSE, FALSE, NULL );
return NULL == *cond ? GetLastError() : 0;
}
int sp_thread_cond_destroy( sp_thread_cond_t * cond )
{
int ret = CloseHandle( *cond );
return 0 == ret ? GetLastError() : 0;
}
/*
Caller MUST be holding the mutex lock; the
lock is released and the caller is blocked waiting
on 'cond'. When 'cond' is signaled, the mutex
is re-acquired before returning to the caller.
*/
int sp_thread_cond_wait( sp_thread_cond_t * cond, sp_thread_mutex_t * mutex )
{
int ret = 0;
sp_thread_mutex_unlock( mutex );
ret = WaitForSingleObject( *cond, INFINITE );
sp_thread_mutex_lock( mutex );
return WAIT_OBJECT_0 == ret ? 0 : GetLastError();
}
int sp_thread_cond_signal( sp_thread_cond_t * cond )
{
int ret = SetEvent( *cond );
return 0 == ret ? GetLastError() : 0;
}
sp_thread_t sp_thread_self()
{
return GetCurrentThreadId();
}
int sp_thread_attr_init( sp_thread_attr_t * attr )
{
memset( attr, 0, sizeof( sp_thread_attr_t ) );
return 0;
}
int sp_thread_attr_destroy( sp_thread_attr_t * attr )
{
return 0;
}
int sp_thread_attr_setdetachstate( sp_thread_attr_t * attr, int detachstate )
{
attr->detachstate = detachstate;
return 0;
}
int sp_thread_attr_setstacksize( sp_thread_attr_t * attr, size_t stacksize )
{
attr->stacksize = stacksize;
return 0;
}
int sp_thread_create( sp_thread_t * thread, sp_thread_attr_t * attr,
sp_thread_func_t myfunc, void * args )
{
// _beginthreadex returns 0 on an error
HANDLE h = 0;
if( NULL != attr ) {
h = (HANDLE)_beginthreadex( NULL, attr->stacksize, myfunc, args, 0, thread );
} else {
h = (HANDLE)_beginthreadex( NULL, 0, myfunc, args, 0, thread );
}
return h > 0 ? 0 : GetLastError();
}
#endif