/*****************************************************
copyright (C), 2014-2015, Lighting Studio. Co., Ltd.
File name:
Author:Jerey_Jobs Version:0.1 Date:
Description:
Funcion List:
*****************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#define N 10
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condA_B = PTHREAD_COND_INITIALIZER;
pthread_cond_t condB_C = PTHREAD_COND_INITIALIZER;
pthread_cond_t condC_A = PTHREAD_COND_INITIALIZER;
int flagA = 0,flagB = 0,flagC = 0;
void *th_fun1(void *arg)
{
int i = 0;
char *name = (char *)arg;
while(i < N)
{
pthread_mutex_lock(&mutex);
flagA = 1;
pthread_cond_wait(&condC_A, &mutex);
flagA = 0;
printf("%c:%d-->%lx\n", *name, i, pthread_self());
while(!flagB)
{
pthread_mutex_unlock(&mutex);
usleep(10);
pthread_mutex_lock(&mutex);
}
pthread_cond_signal(&condA_B);
pthread_mutex_unlock(&mutex);
i++;
usleep(10);
}
flagA = 1;
}
void *th_fun2(void *arg)
{
int i = 0;
char *name = (char *)arg;
while(i < N)
{
pthread_mutex_lock(&mutex);
flagB = 1;
pthread_cond_wait(&condA_B, &mutex);
flagB = 0;
printf("%c:%d-->%lx\n",*name, i, pthread_self());
while(!flagC)
{
pthread_mutex_unlock(&mutex);
usleep(10);
pthread_mutex_lock(&mutex);
}
pthread_cond_signal(&condB_C);
pthread_mutex_unlock(&mutex);
i++;
usleep(10);
}
}
void *th_fun3(void * arg)
{
int i = 0;
char *name = (char *)arg;
while(i < N)
{
pthread_mutex_lock(&mutex);
flagC = 1;
pthread_cond_wait(&condB_C, &mutex);
flagC = 0;
printf("%c:%d-->%lx\n", *name, i, pthread_self());
while(!flagA)
{
pthread_mutex_unlock(&mutex);
usleep(10);
pthread_mutex_lock(&mutex);
}
pthread_cond_signal(&condC_A);
pthread_mutex_unlock(&mutex);
i++;
usleep(10);
}
}
int main()
{
pthread_t th1, th2, th3;
int ret = 0;
char name1 = 'A', name2 = 'B', name3 = 'C';
int *p1 = (int *) &name1;
int *p2 = (int *) &name2;
int *p3 = (int *) &name3;
ret = pthread_create(&th1, NULL, th_fun1, (void *)p1);
if(ret)
{
printf("create th_fun1 error!\n");
return 1;
}
usleep(10);
ret = pthread_create(&th2, NULL, th_fun2, (void *)p2);
if(ret)
{
printf("create th_fun2 error!\n");
return 1;
}
usleep(10);
ret = pthread_create(&th3, NULL, th_fun3, (void *)p3);
if(ret)
{
printf("create th_fun3 error!\n");
return 1;
}
pthread_cond_broadcast(&condC_A);
pthread_join(th1, NULL);
printf("th1 finished!\n");
pthread_join(th2, NULL);
printf("th2 finished!\n");
pthread_join(th3, NULL);
printf("th3 finished!\n");
return 0;
}