Created
May 19, 2015 04:19
-
-
Save minhnhdo/417bd3dde12f86f8d034 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
#include <pthread.h> | |
#include <stdio.h> | |
#include <unistd.h> | |
#define TOTAL_THREADS 2 | |
#define MAX 10 | |
int shared = 0; | |
int turn = 0; | |
int started = 0; | |
pthread_mutex_t mutex; | |
pthread_cond_t cond; | |
void *increment(void *arg) | |
{ | |
int thread_no = *((int *) arg); | |
pthread_mutex_lock(&mutex); | |
while (1) { | |
if (!started || turn != thread_no) { | |
pthread_cond_wait(&cond, &mutex); | |
} | |
if(shared <= MAX) { | |
printf("%d|%d\n", thread_no, shared++); | |
turn = !turn; | |
pthread_cond_signal(&cond); | |
} else { | |
turn = !turn; | |
pthread_cond_signal(&cond); | |
break; | |
} | |
} | |
pthread_mutex_unlock(&mutex); | |
return NULL; | |
} | |
int main(void) | |
{ | |
pthread_t threads[TOTAL_THREADS]; | |
int args[TOTAL_THREADS], index; | |
pthread_mutex_init(&mutex, NULL); | |
pthread_cond_init(&cond, NULL); | |
for (index = 0; index < TOTAL_THREADS; ++index) { | |
args[index] = index; | |
pthread_create(&threads[index], NULL, increment, (void *) &args[index]); | |
} | |
pthread_mutex_lock(&mutex); | |
started = 1; | |
turn = 0; | |
pthread_cond_signal(&cond); // send the first signal | |
pthread_mutex_unlock(&mutex); | |
for (index = 0; index < TOTAL_THREADS; ++index) { | |
pthread_join(threads[index], NULL); | |
} | |
pthread_mutex_destroy(&mutex); | |
pthread_cond_destroy(&cond); | |
printf("Done!\n"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment