Last active
August 29, 2015 14:03
-
-
Save manku-timma/8d3166229659540d39ba to your computer and use it in GitHub Desktop.
Using pthread apis
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
#include <stdio.h> | |
#include <pthread.h> | |
long state = 0; | |
pthread_mutex_t state_mutex = PTHREAD_MUTEX_INITIALIZER; | |
pthread_cond_t state_cond = PTHREAD_COND_INITIALIZER; | |
void* compute(void* arg) { | |
pthread_mutex_lock(&state_mutex); | |
printf("child: %lu\n", state); | |
while (state == 0) { | |
pthread_cond_wait(&state_cond, &state_mutex); | |
} | |
state = (long)arg; | |
printf("child: %lu\n", state); | |
pthread_mutex_unlock(&state_mutex); | |
pthread_exit(NULL); | |
} | |
int main() { | |
pthread_t child; | |
printf("parent: begin\n"); | |
pthread_create(&child, NULL, compute, (void*)1729); | |
sleep(1); | |
pthread_mutex_lock(&state_mutex); | |
printf("parent: %lu\n", state); | |
state = 1000; | |
pthread_cond_signal(&state_cond); | |
printf("parent: %lu\n", state); | |
pthread_mutex_unlock(&state_mutex); | |
void* ret; | |
pthread_join(child, &ret); | |
printf("parent: end\n"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment