该程序使三个线程合作打印ABC。
#include <iostream>
#include <pthread.h>
using namespace std;
int state[3];
int count = 0;
void *thread_fun1(void *arg)
{
while(count < 10)
{
while(state[0] == 1)
{
state[0] = 0;
cout << "A";
state[1] = 1;
}
}
}
void *thread_fun2(void *arg)
{
while(count < 10){
while(state[1] == 1)
{
state[1] = 0;
cout << "B";
state[2] = 1;
}
}
}
void *thread_fun3(void *arg)
{
while(count < 10){
while(state[2] == 1)
{
state[2] = 0;
cout << "C"<<endl;
count++;
state[0] = 1;
}
}
}
int main()
{
for(int i = 0;i<3;i++)
state[i] = 0;
state[0] = 1;
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
pthread_create(&thread1, NULL, thread_fun1, NULL);
pthread_create(&thread2, NULL, thread_fun2, NULL);
pthread_create(&thread3, NULL, thread_fun3, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_join(thread3, NULL);
cout << "over!" << endl;
return 0;
}
结果如下
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
ABC
over!