您的位置:首页 > 其它

使多线程按顺序执行的一种方法

2014-04-25 14:02 267 查看
该程序使三个线程合作打印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;
}
结果如下
ABCABCABCABCABCABCABCABCABCABCover!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息