Tony L
BAN USERImplementation using mutex and condition var.
//
// main.c
// EvenOddCreat
//
#include <stdio.h>
#include <pthread.h>
pthread_t odd_thread, even_thread;
pthread_mutex_t lock;
pthread_cond_t cond;
int turn;
int max;
void* even_run(void* data)
{
int* max = data;
for(int i=0; i<*max; i+=2)
{
pthread_mutex_lock(&lock);
while (turn != 0)
{
pthread_cond_wait(&cond, &lock);
}
turn = 1;
pthread_mutex_unlock(&lock);
printf("%d,", i);
pthread_cond_signal(&cond);
}
return NULL;
}
void* odd_run(void* data)
{
int* max = data;
for(int i=1; i<*max; i+=2)
{
pthread_mutex_lock(&lock);
while (turn != 1)
{
pthread_cond_wait(&cond, &lock);
}
turn = 0;
pthread_mutex_unlock(&lock);
printf("%d,", i);
pthread_cond_signal(&cond);
}
return NULL;
}
int main(int argc, const char * argv[])
{
turn = 0;
max = 10;
pthread_cond_init(&cond, NULL);
pthread_mutex_init(&lock, NULL);
pthread_create(&even_thread, NULL, &even_run, &max);
pthread_create(&odd_thread, NULL, &odd_run, &max);
pthread_join(odd_thread, NULL);
pthread_join(even_thread, NULL);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}
The mutex and cond vars should be destroyed at the end of main func. And I edited my submit to reflect that change. Apologize for my carelessness.
- Tony L February 22, 2014