互斥锁+条件变量实现版本
#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
using namespace std;
condition_variable cv;//条件变量
mutex mx;//互斥量
int isReady = 0;//初始化为0
void printf_1()
{
unique_lock<mutex> lc(mx);
int i = 0;
while(i < 10)
{
while(isReady != 0)//如果还没有准备好 那么久开始等待,并且释放锁
cv.wait(lc);
cout << "A" ;
isReady = 1;
i++;
cv.notify_all();
}
}
void printf_2()
{
unique_lock<mutex> lc(mx);
int i = 0;
while(i < 10)
{
while(isReady != 1)
cv.wait(lc);
cout << "B" ;
isReady = 2;
i++;
cv.notify_all(); //我已经打印完了 轮到别的线程打印了
}
}
void printf_3()
{
unique_lock<mutex> lc(mx);
int i = 0;
while (i < 10)
{
while (isReady != 2)
cv.wait(lc);
cout << "C" ;
isReady = 0;
i++;
cv.notify_all(); //我已经打印完了,轮到别的线程打印了
}
}
int main()
{
thread t1(printf_1);
thread t2(printf_2);
thread t3(printf_3);
t1.join();
t2.join();
t3.join();
return 0;
}
运行截图如下:
信号量实现版本
#include <iostream>
#include <thread>
#include <semaphore.h>
using namespace std;
sem_t sem1;
sem_t sem2;
sem_t sem3;
void pthread_fun1()
{
int i = 0;
for (; i < 10; ++i)
{
sem_wait(&sem1); //P操作
cout << "A" ;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
sem_post(&sem2); //V操作
}
}
void pthread_fun2()
{
int i = 0;
for (; i < 10; ++i)
{
sem_wait(&sem2);
cout << "B" ;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
sem_post(&sem3);
}
}
void pthread_fun3()
{
int i = 0;
for (; i < 10; ++i)
{
sem_wait(&sem3);
cout << "C" ;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
sem_post(&sem1);
}
}
int main()
{
sem_init(&sem1, 0, 1); //初始化
sem_init(&sem2, 0, 0);
sem_init(&sem3, 0, 0);
thread s1(pthread_fun1);
thread s2(pthread_fun2);
thread s3(pthread_fun3);
s1.join();
s2.join();
s3.join();
sem_destroy(&sem1); //销毁信号量
sem_destroy(&sem2);
sem_destroy(&sem3);
return 0;
}