多线程顺序执行实现方式
方式一 互斥锁
#include <time.h>
#include <unistd.h>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
int flag = 1;
mutex mtx;
void PrintA() {
for (;;) {
unique_lock<mutex> locker(mtx);
if (flag == 1) {
cout << "A" << endl;
flag = 2;
}
}
}
void PrintB() {
for (;;) {
unique_lock<mutex> locker(mtx);
if (flag == 2) {
cout << "B" << endl;
flag = 3;
}
}
}
void PrintC() {
for (;;) {
lock_guard<mutex> locker(mtx);
if (flag == 3) {
cout << "C" << endl;
flag = 1;
}
}
}
int main() {
thread th1(PrintA);
thread th2(PrintB);
thread th3(PrintC);
for (;;) {
sleep(1);
}
}
方式二 信号量
#include <semaphore.h>
#include <time.h>
#include <unistd.h>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
using namespace std;
int flag = 1;
condition_variable con;
mutex mtx;
sem_t sem1;
sem_t sem2;
sem_t sem3;
void PrintA() {
for (;;) {
sem_wait(&sem1);
cout << "A" << endl;
sem_post(&sem2);
}
}
void PrintB() {
for (;;) {
sem_wait(&sem2);
cout << "B" << endl;
sem_post(&sem3);
}
}
void PrintC() {
for (;;) {
sem_wait(&sem3);
cout << "C" << endl;
cout << "=============" << endl;
sem_post(&sem1);
}
}
int main() {
sem_init(&sem1, 0, 1);
sem_init(&sem2, 0, 0);
sem_init(&sem3, 0, 0);
thread th1(PrintA);
thread th2(PrintB);
thread th3(PrintC);
for (;;) {
sleep(1);
}
sem_destroy(&sem1);
sem_destroy(&sem2);
sem_destroy(&sem3);
}