#include <pthread.h>
#include <cstdio>
#include <unistd.h>
const int THREAD_NUMBER = 3;
// 同步与互斥
pthread_mutex_t mutex;
pthread_mutex_t thread_mutex[THREAD_NUMBER];
pthread_cond_t thread_cond[THREAD_NUMBER];
pthread_cond_t cond;
int a[3] = {0}; //用于线程与主线程通信,表示 子线程已经起动
//
void *thread_func(void *arg);
int main(int argc, char **argv)
{
pthread_t tids[THREAD_NUMBER];
for (int i = 0; i < THREAD_NUMBER; ++i)
{
pthread_mutex_init(&thread_mutex[i], NULL);
pthread_cond_init(&thread_cond[i], NULL);
}
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
for (int i = 0; i < THREAD_NUMBER; ++i)
{
pthread_create(&tids[i], NULL, thread_func, (void *)i);
}
while(1)
{
int i = 0;
for(; i<THREAD_NUMBER; i++)
{
if(a[i]==0)
{
break;
}
}
if(i>2)
{
break;
}
sleep(1);
}
pthread_cond_signal(&thread_cond[0]);
for (int i = 0; i < THREAD_NUMBER; ++i)
{
pthread_join(tids[i], NULL);
}
printf("\n");
return 0;
}
void *thread_func(void *arg)
{
int id = *(int*)(&arg);
char ch = 'A' + id;
int count = 10;
a[id] = 1;
while (count--)
{
pthread_cond_wait(&thread_cond[id], &thread_mutex[id]);
printf("%c", ch);
pthread_cond_signal(&thread_cond[(id+1)%3]);
}
return (void *)0;
}