Created
June 26, 2019 22:01
-
-
Save wangbj/3f2eec4f7f56d4aa252d21ae515f10a4 to your computer and use it in GitHub Desktop.
pthread cond var test, block on child thread
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
/* build with `-O -pthread -D_GNU_SOURCE=1` */ | |
#include <unistd.h> | |
#include <pthread.h> | |
#include <assert.h> | |
static pthread_cond_t run_first = PTHREAD_COND_INITIALIZER; | |
static pthread_mutex_t cond_mutex = PTHREAD_MUTEX_INITIALIZER; | |
static void* second_thread(void* param) { | |
assert(pthread_cond_wait(&run_first, &cond_mutex) == 0); | |
assert(write(STDOUT_FILENO, "second\n", 7) == 7); | |
assert(pthread_mutex_destroy(&cond_mutex) == 0); | |
return NULL; | |
} | |
static void* first_thread(void* param) { | |
assert(pthread_cond_signal(&run_first) == 0); | |
assert(write(STDOUT_FILENO, "first\n", 6) == 6); | |
return NULL; | |
} | |
int main(int argc, char* argv[]) | |
{ | |
pthread_t first, second; | |
assert(pthread_create(&second, NULL, second_thread, NULL) == 0); | |
assert(pthread_create(&first, NULL, first_thread, NULL) == 0); | |
assert(pthread_join(first, NULL) == 0); | |
assert(pthread_join(second, NULL) == 0); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment