Created
March 25, 2018 03:51
-
-
Save croepha/d3c69bdf4195809e1d7e3536ec3ea6a6 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
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