Skip to content

Instantly share code, notes, and snippets.

@trevnorris trevnorris/sem-simple.c
Last active Oct 22, 2017

Embed
What would you like to do?
#include <stdio.h>
#include <assert.h>
#include "uv.h"
#define ITER 1e6
#define ACCESS_ONCE(type, var) \
(*(volatile type*) &(var))
static uv_mutex_t mutex;
static uv_sem_t sem_main;
static uv_sem_t sem_thread;
static uv_thread_t thread;
static int cntr = ITER;
static void thread_cb(void* arg) {
while (ACCESS_ONCE(int, cntr) > 0) {
uv_sem_post(&sem_main);
uv_sem_wait(&sem_thread);
}
}
int main() {
assert(0 == uv_sem_init(&sem_main, 0));
assert(0 == uv_sem_init(&sem_thread, 0));
assert(0 == uv_mutex_init(&mutex));
assert(0 == uv_thread_create(&thread, thread_cb, NULL));
uint64_t time = uv_hrtime();
while (--ACCESS_ONCE(int, cntr) > 0) {
uv_sem_wait(&sem_main);
uv_sem_post(&sem_thread);
}
time = uv_hrtime() - time;
printf("%f us/op\n", time / 1e3 / ITER);
uv_thread_join(&thread);
uv_mutex_destroy(&mutex);
uv_sem_destroy(&sem_main);
uv_sem_destroy(&sem_thread);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.