/*
题目:
output "ABCABCABC": threadFunc_A just print "A", threadFunc_B just print "B", threadFunc_C just print "C".
*/
#include <pthread.h>
#include <iostream>
using namespace std;
bool is_A_ok = true;
bool is_B_ok = false;
bool is_C_ok = false;
static void* threadFunc_A(void* param)
{
int i = 3;
while(i > 0)
{
if(is_A_ok)
{
cout<<"A";
--i;
is_A_ok = false;
is_B_ok = true;
}
}
return NULL;
}
static void* threadFunc_B(void* param)
{
int i = 3;
while(i > 0)
{
if(is_B_ok)
{
cout<<"B";
--i;
is_B_ok = false;
is_C_ok = true;
}
}
return NULL;
}
static void* threadFunc_C(void* param)
{
int i = 3;
while(i > 0)
{
if(is_C_ok)
{
cout<<"C";
--i;
is_C_ok = false;
is_A_ok = true;
}
}
cout<<endl;
return NULL;
}
int main(int argc, char *argv[])
{
int s=0;
pthread_t tA;
s = pthread_create(&tA, NULL, &threadFunc_A, NULL);;
if(s!=0)
{
cout<<"Error happend: pthread_create, A"<<endl;
return EXIT_FAILURE;
}
pthread_t tB;
s = pthread_create(&tB, NULL, &threadFunc_B, NULL);;
if(s!=0)
{
cout<<"Error happend: pthread_create, B"<<endl;
return EXIT_FAILURE;
}
pthread_t tC;
s = pthread_create(&tC, NULL, &threadFunc_C, NULL);;
if(s!=0)
{
cout<<"Error happend: pthread_create, C"<<endl;
return EXIT_FAILURE;
}
pthread_join (tA, NULL);
pthread_join (tB, NULL);
pthread_join (tC, NULL);
return EXIT_SUCCESS;
}
编程练习:使用变量控制多线程调用顺序,布布扣,bubuko.com
原文:http://blog.csdn.net/walle_love_eva/article/details/21010869