1.使用linux条件变量
using namespace std;
pthread_mutex_t mt = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD COND_INITIALIZER;
pthread_cond_t cond2= PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER;
int flag = 0;
void fa()
{
int n = 10;
while (n--)
{
pthread_mutex_lock(&mt);
if (flag != 0)
{
pthread_cond_wait(&cond1, &mt);
}
printf("A");
flag = 1;
pthread_mutex_unlock(&mt);
pthread_cond_signal(&cond2);
}
}
void fb()
{
int n = 10;
while (n--)
{
pthread_mutex_lock(&mt);
if (flag I= 1)
{
pthread_cond_wait(&cond2, &mt);
}
printf("B");
flag = 2;
pthread_mutex_unlock(&mt);
pthread_cond_signal(&cond3);
}
}
void fc()
{
int n = 10;
while (n--)
{
pthread_mutex_lock(&mt);
if (flag != 2)
{
pthread_cond_wait(&cond3, &mt);
}
printf("C");
flag = 0;
pthread_mutex_unlock(&mt);
pthread_cond_signal(&cond1);
}
}
int main()
{
pthread_t t1, t2, t3;
pthread_create(&t1, NULL, fa, NULL);
pthread_create(&t2, NULL, fb, NULL);
pthread_create(&t3, NULL, fc, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
pthread_mutex_destroy(&mt);
pthread_cond_destroy(&cond1);
pthread_cond_destroy(&cond2);
pthread_cond_destroy(&cond3);
}
2.使用C++多线程库
#include<mutex>
#include<condition_variable>
#include<thread>
using namespace std;
int flag =0;
mutex mt;
condition_variable cl;
void f1()
{
int n = 10;
while (n--)
unique_lock<mutex> lm(mt);
while(flag!=0)
{
c1.wait(lm);
}
cout << "A";
flag = 1;
c1.notify_all();
}
void f2()
{
int n= 10;
while (n--)
unique_lock<mutex> lm(mt);
while (flag != 1)
{
c1.wait(lm);
}
cout << "B";
flag = 2;
c1.notify_all();
}
void f3()
{
int n = 10;
while (n--)
unique_lock<mutex> lm(mt);
while (flag != 2)
{
c1.wait(lm);
}
cout << "C" << n << endl;
flag = 0;
c1.notify_all();
}
int main()
{
thread t1(f1);
thread t2(f2);
thread t3(f3);
t1.join();
t2.join();
t3.join();
}
3.使用linux信号量
#include<semaphore.h>
#include<pthread.h>
#include<stdio.h>
sem_t seml, sem2, sem3;
void f1()
{
int n= 10;
while(n--)
{
sem_wait(&sem1);
cout << "A";
sem_post(&sem2);
}
}
void f2()
{
int n = 10;
while(n--)
{
sem_wait(&sem2);
cout << "B";
sem_post(&sem3);
}
}
void f3()
{
int n = 10;
while(n--)
{
sem_wait(&sem3);
cout << "C" << endl;
sem_post(&sem1);
}
}
int main()
{
sem_init(&seml, 0, 1);
sem_init(&sem2, 0, 0);
sem_init(&sem3, 0, 6);
pthread_t t1, t2, t3;
pthread_create(&t1, NULL, f1, NULL);
pthread_create(&t2, NULL, f2, NULL);
pthread_create(&t3, NULL, f3, NULL);
pthread_join(t1, NULL);|
pthread_join(t2, NULL);
pthread_join(t3, NULL);
}