-
-
Save addaleax/2f7974fe45b634e5c20fa0ad1ea7ce93 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <pthread.h> | |
#include <semaphore.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <stdio.h> | |
static void* worker(void* arg) { | |
int ret = sem_post((sem_t*) arg); | |
if (ret == -1) { | |
perror("sem_post() failed"); | |
abort(); | |
} | |
return NULL; | |
} | |
static void test() { | |
int nthreads = 4; | |
int i, ret; | |
pthread_t* threads = malloc(sizeof(pthread_t) * nthreads); | |
sem_t sem; | |
ret = sem_init(&sem, 0, 0); | |
if (ret == -1) { | |
perror("sem_init() failed"); | |
abort(); | |
} | |
for (i = 0; i < nthreads; ++i) { | |
ret = pthread_create(threads + i, NULL, worker, &sem); | |
if (ret != 0) { | |
errno = ret; | |
perror("pthread_create() failed"); | |
abort(); | |
} | |
} | |
for (i = 0; i < nthreads; ++i) { | |
do { | |
ret = sem_wait(&sem); | |
} while (ret == -1 && errno == EINTR); | |
if (ret == -1) { | |
perror("sem_wait() failed"); | |
abort(); | |
} | |
} | |
ret = sem_destroy(&sem); | |
if (ret == -1) { | |
perror("sem_destroy() failed"); | |
abort(); | |
} | |
memset(&sem, 0xac, sizeof(sem)); | |
for (i = 0; i < nthreads; ++i) { | |
ret = pthread_join(threads[i], NULL); | |
if (ret != 0) { | |
errno = ret; | |
perror("pthread_join() failed"); | |
abort(); | |
} | |
} | |
free(threads); | |
} | |
int main() { | |
int i; | |
for (i = 0; i < 100000; ++i) | |
test(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment