编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
程序代码如下:
#include<iostream>
#include<cstdlib>
using namespace std;
#ifdef __cplusplus
extern "C"
{
#endif
#include<pthread.h>
#include<semaphore.h>
#ifdef __cplusplus
}
#endif
sem_t sem1,sem2,sem3;
int var = 1;
void *PrintA(void *ptr)
{
int i;
for(i = 0; i < 10; i++)
{
sem_wait(&sem1);
cout<<"A";
sem_post(&sem2);
}
return NULL;
}
void *PrintB(void *ptr)
{
for(int i = 0; i < 10; i++)
{
sem_wait(&sem2);
cout<<"B";
sem_post(&sem3);
}
return NULL;
}
void *PrintC(void *ptr)
{
for(int i = 0; i < 10; i++)
{
sem_wait(&sem3);
cout<<"C";
sem_post(&sem1);
}
return NULL;
}
void init_thread()
{
int rc1,rc2,rc3;
pthread_t thread1,thread2,thread3;
sem_init(&sem1,0,0);
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
if( (rc1 = pthread_create(&thread1,NULL,PrintA,NULL) ))
{
cout<<"create thread is failed"<<endl;
exit(1);
}
if( (rc2 = pthread_create(&thread2,NULL,PrintB,NULL) ))
{
cout<<"create thread is failed"<<endl;
exit(1);
}
if( (rc3 = pthread_create(&thread3,NULL,PrintC,NULL) ))
{
cout<<"create thread is failed"<<endl;
exit(1);
}
sem_post(&sem1);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
pthread_join(thread3,NULL);
}
int main(int argc,char *argv[])
{
init_thread();
cout<<endl;
return 0;
}