实现简单的顺序打印
主要功能:printa()、printl()、printi()
定义三个信号量依次给三个进程上锁,并且通过其他进程来给自己解锁
#include<iostream>
#include<thread>
#include<mutex>
#include"semaphore.h"
using namespace std;
//三个信号量相当于三个锁,可以等价替换
semaphore sem1(1), sem2(0), sem3(0);
//mutex mtx1,mtx2,mtx3;
//mtx2.lock();mtx3.lock();
void printa() {
for (int i = 0; i < 10000; i++) {
sem1.wait();//mtx1.lock();
cout << 'a';
sem2.signal();//mtx2.unlock();
}
}
void printl() {
for (int i = 0; i < 10000; i++) {
sem2.wait();//mtx2.lock();
cout << 'l';
sem3.signal();//mtx3.unlock();
}
}
void printi() {
for (int i = 0; i < 10000; i++) {
sem3.wait();//mtx3.lock();
cout << 'i';
sem1.signal();//mtx1.unlock();
}
}
int main() {
thread thread1(printa);
thread thread2(printl);
thread thread3(printi);
thread1.join();
thread2.join();
thread3.join();
}
semaphore.h可以看我前面的博客