Last active
August 29, 2015 14:10
-
-
Save trevnorris/74998a1ddd19575f8a1e to your computer and use it in GitHub Desktop.
bounce back and forth between threads using semaphores
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
/* Compiled with | |
* clang -pthread -fno-omit-frame-pointer -Wall -g -fstrict-aliasing -O3 \ | |
* -o sem-bounce sem-bounce.c libuv.a -Iuv/include | |
*/ | |
#include "uv.h" | |
#define ITER 1e6 | |
static uv_thread_t thread; | |
static uv_sem_t msem; | |
static uv_sem_t tsem; | |
static unsigned int iter; | |
static void tq_thread_cb(void* arg) { | |
for (;;) { | |
//while (uv_sem_trywait(&tsem) != 0); | |
uv_sem_wait(&tsem); | |
uv_sem_post(&msem); | |
if (ITER - 1 == iter) | |
break; | |
} | |
} | |
int main() { | |
/* initialize */ | |
uv_thread_create(&thread, tq_thread_cb, NULL); | |
uv_sem_init(&msem, 0); | |
uv_sem_init(&tsem, 0); | |
iter = 0; | |
for (; iter < ITER; iter++) { | |
uv_sem_post(&tsem); | |
uv_sem_wait(&msem); | |
//while (uv_sem_trywait(&msem) != 0); | |
} | |
/* cleanup */ | |
uv_sem_destroy(&msem); | |
uv_sem_destroy(&tsem); | |
uv_thread_join(&thread); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment