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