Created
June 19, 2018 15:32
-
-
Save ethercflow/6ef64544928dd2c17f94243d7b0ee505 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <stdlib.h> | |
| #include <unistd.h> | |
| #include <pthread.h> | |
| pthread_mutex_t lock; | |
| pthread_cond_t cond; | |
| static unsigned counter; | |
| static void dec_counter(void) { | |
| pthread_mutex_lock(&lock); | |
| while (counter == 0) { | |
| pthread_cond_wait(&cond, &lock); | |
| } | |
| counter -= 1; | |
| pthread_mutex_unlock(&lock); | |
| } | |
| static void inc_counter(void) { | |
| pthread_mutex_lock(&lock); | |
| if (counter == 0) { | |
| sleep(3); | |
| pthread_cond_signal(&cond); | |
| } | |
| counter += 1; | |
| pthread_mutex_unlock(&lock); | |
| } | |
| void *thread_main(void *arg) { | |
| int i = (int)arg; | |
| if (i == 0) { | |
| while (1) { | |
| dec_counter(); | |
| } | |
| } else { | |
| while (1) { | |
| inc_counter(); | |
| } | |
| } | |
| return NULL; | |
| } | |
| int main(void) { | |
| pthread_t t[2]; | |
| int i; | |
| for (i = 0; i < 2; i++) { | |
| pthread_create(&t[i], NULL, thread_main, (void*)i); | |
| } | |
| for (i = 0; i < 2; i++) { | |
| pthread_join(t[i], NULL); | |
| } | |
| pthread_cond_destroy(&cond); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment