Created
June 26, 2019 22:00
-
-
Save wangbj/5d3fdc16b3c61f71a0fd2844dcef66da to your computer and use it in GitHub Desktop.
pthread cond var test, wait on main 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 void* second_thread(void* param) { | |
assert(write(STDOUT_FILENO, "second\n", 7) == 7); | |
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; | |
pthread_mutex_t cond_mutex = PTHREAD_MUTEX_INITIALIZER; | |
assert(pthread_create(&first, NULL, first_thread, NULL) == 0); | |
assert(pthread_cond_wait(&run_first, &cond_mutex) == 0); | |
assert(pthread_mutex_destroy(&cond_mutex) == 0); | |
assert(pthread_create(&second, NULL, second_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