1 /************************************************************/
2 #ifndef _MSC_VER
3 /************************************************************/
4
5
6 #include <pthread.h>
7
8 /* don't include <semaphore.h>, it is not available on OS/X */
9
10 typedef struct {
11 pthread_mutex_t mutex1;
12 pthread_cond_t cond1;
13 unsigned int value;
14 } sem_t;
15
sem_init(sem_t * sem,int pshared,unsigned int value)16 static int sem_init(sem_t *sem, int pshared, unsigned int value)
17 {
18 assert(pshared == 0);
19 sem->value = value;
20 return (pthread_mutex_init(&sem->mutex1, NULL) ||
21 pthread_cond_init(&sem->cond1, NULL));
22 }
23
sem_post(sem_t * sem)24 static int sem_post(sem_t *sem)
25 {
26 pthread_mutex_lock(&sem->mutex1);
27 sem->value += 1;
28 pthread_cond_signal(&sem->cond1);
29 pthread_mutex_unlock(&sem->mutex1);
30 return 0;
31 }
32
sem_wait(sem_t * sem)33 static int sem_wait(sem_t *sem)
34 {
35 pthread_mutex_lock(&sem->mutex1);
36 while (sem->value == 0)
37 pthread_cond_wait(&sem->cond1, &sem->mutex1);
38 sem->value -= 1;
39 pthread_mutex_unlock(&sem->mutex1);
40 return 0;
41 }
42
43
44 /************************************************************/
45 #else
46 /************************************************************/
47
48
49 /* Very quick and dirty, just what I need for these tests.
50 Don't use directly in any real code!
51 */
52
53 #include <Windows.h>
54 #include <assert.h>
55
56 typedef HANDLE sem_t;
57 typedef HANDLE pthread_t;
58
sem_init(sem_t * sem,int pshared,unsigned int value)59 static int sem_init(sem_t *sem, int pshared, unsigned int value)
60 {
61 assert(pshared == 0);
62 assert(value == 0);
63 *sem = CreateSemaphore(NULL, 0, 999, NULL);
64 return *sem ? 0 : -1;
65 }
66
sem_post(sem_t * sem)67 static int sem_post(sem_t *sem)
68 {
69 return ReleaseSemaphore(*sem, 1, NULL) ? 0 : -1;
70 }
71
sem_wait(sem_t * sem)72 static int sem_wait(sem_t *sem)
73 {
74 WaitForSingleObject(*sem, INFINITE);
75 return 0;
76 }
77
myThreadProc(LPVOID lpParameter)78 static DWORD WINAPI myThreadProc(LPVOID lpParameter)
79 {
80 void *(* start_routine)(void *) = (void *(*)(void *))lpParameter;
81 start_routine(NULL);
82 return 0;
83 }
84
pthread_create(pthread_t * thread,void * attr,void * start_routine (void *),void * arg)85 static int pthread_create(pthread_t *thread, void *attr,
86 void *start_routine(void *), void *arg)
87 {
88 assert(arg == NULL);
89 *thread = CreateThread(NULL, 0, myThreadProc, start_routine, 0, NULL);
90 return *thread ? 0 : -1;
91 }
92
93
94 /************************************************************/
95 #endif
96 /************************************************************/
97