编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
使用条件变量来实现:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
static pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t condA ;
static pthread_cond_t condB ;
static pthread_cond_t condC ;
void* threadA(void *arg)
{
int a =10;
while(a--)
{
//sleep(2);
//printf("A begin.\n");
pthread_mutex_lock(&mtx);
//printf("A wait.\n");
pthread_cond_wait(&condC,&mtx);
printf("A.\n");
pthread_mutex_unlock(&mtx);
pthread_cond_signal(&condA);
}
}
void* threadB(void *arg)
{
int b=10;
while(b--)
{
//sleep(2);
//printf("B begin.\n");
pthread_mutex_lock(&mtx);
//printf("B wait.\n");
pthread_cond_wait(&condA,&mtx);
printf("B.\n");
pthread_mutex_unlock(&mtx);
pthread_cond_signal(&condB);
}
}
void* threadC(void *arg)
{
int c=10;
while(c--)
{
//sleep(2);
//printf("C begin.\n");
pthread_mutex_lock(&mtx);
//printf("C wait.\n");
pthread_cond_wait(&condB,&mtx);
printf("C.\n");
pthread_mutex_unlock(&mtx);
pthread_cond_signal(&condC);
}
}
int main (void *arg)
{
pthread_t tidA;
pthread_t tidB;
pthread_t tidC;
pthread_cond_init(&condA,NULL);
pthread_cond_init(&condB,NULL);
pthread_cond_init(&condC,NULL);
pthread_create(&tidA,NULL,&threadA,NULL);
pthread_create(&tidB,NULL,&threadB,NULL);
pthread_create(&tidC,NULL,&threadC,NULL);
printf("main begin..\n");
sleep(4);
pthread_cond_signal(&condC);
pthread_join(tidA,NULL);
pthread_join(tidB,NULL);
pthread_join(tidC,NULL);
return 0;
}