Skip to content

Instantly share code, notes, and snippets.

@croepha
Created March 25, 2018 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save croepha/d3c69bdf4195809e1d7e3536ec3ea6a6 to your computer and use it in GitHub Desktop.
Save croepha/d3c69bdf4195809e1d7e3536ec3ea6a6 to your computer and use it in GitHub Desktop.
bool thread2_is_waiting_for_sync = false;
auto mutex = PTHREAD_MUTEX_INITIALIZER;
auto cond_m = PTHREAD_MUTEX_INITIALIZER;
auto cond = PTHREAD_COND_INITIALIZER ;
void* thread1(void*) {
mutex = PTHREAD_MUTEX_INITIALIZER;
cond_m = PTHREAD_MUTEX_INITIALIZER;
cond = PTHREAD_COND_INITIALIZER ;
assert(!pthread_mutex_lock(&mutex));
pthread_create(&thread_handle, NULL, thread2, NULL);
for(;;) {
// ...
if (thread2_is_waiting_for_sync) {
assert(!pthread_mutex_unlock(&mutex));
assert(!pthread_mutex_lock(&cond_m));
while (thread2_is_waiting_for_sync) {
assert(!pthread_cond_wait(&cond, &cond_m));
}
assert(!pthread_mutex_unlock(&cond_m));
assert(!pthread_mutex_lock(&mutex));
}
// ...
}
}
void* thread1(void*) {
for (;;) {
block_on_something_for_a_long_time();
assert(!pthread_mutex_lock(&cond_m));
thread2_is_waiting_for_sync = true;
assert(!pthread_mutex_unlock(&cond_m));
assert(!pthread_mutex_lock(&mutex));
assert(!pthread_mutex_lock(&cond_m));
// Do stuff with thread1's data...
thread2_is_waiting_for_sync = false;
assert(!pthread_cond_broadcast(&cond));
assert(!pthread_mutex_unlock(&cond_m));
assert(!pthread_mutex_unlock(&mutex));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment