Commit 6628424b authored by Administrator's avatar Administrator
Browse files

add mutex

parent 48b5a4cc
#include <iostream>
#include <mutex>
#include <queue>
#include <cstdlib>
#include <unistd.h>
#include <thread>
using namespace std;
// 打印日志
void printMsg(string msg) {
cout << msg + "\n";
}
// 线程安全类,该类会被用来初始化一次,然后通过引用传递,给多个线程轮流操作
class ThreadSafeQueue {
private:
// int队列
queue<int> rawQueue;
// 排他锁
mutex m;
public:
// 打印包含线程名的日志
void printLocalMsg(string msg, string name) {
printMsg("[" + name + "] " + msg);
}
// 从队列取值
void retrieveAndDelete(int sleepSec, string name) {
int frontValue = 0;
// 取值之前,加上排他锁,防止其他线程并行操作
m.lock();
printLocalMsg("Lock pop", name);
if (!rawQueue.empty()) {
frontValue = rawQueue.front();
printLocalMsg("Retrieved front value " + to_string(frontValue), name);
rawQueue.pop();
printLocalMsg("Front value popped", name);
}
// 取值完成后,释放锁,使其他线程可以继续操作
printLocalMsg("Unlock pop", name);
m.unlock();
}
// 向队列里存放值
void push(int val, int sleepSec, string name) {
// 存放值之前,加上排他锁,防止其他线程并行操作
m.lock();
printLocalMsg("Lock push", name);
printLocalMsg("Sleep for " + to_string(sleepSec), name);
sleep(sleepSec);
printLocalMsg("Push " + to_string(val), name);
rawQueue.push(val);
// 存放值完成后,释放锁,使其他线程可以继续操作
printLocalMsg("Unlock push", name);
m.unlock();
}
};
// 定义线程操作
void run(int tid, string name, ThreadSafeQueue & tsq) {
// 取随机数 1-5
int random = rand() % 5 + 1;
string msg;
msg = "Start thread " + to_string(tid) + ":" + name
+ " with random " + to_string(random);
tsq.printLocalMsg(msg, name);
// 从线程取值
tsq.retrieveAndDelete(random, name);
// 向线程存放值
tsq.push(random, random, name);
}
int main() {
// Get random int from 1-5
int random = rand() % 5 + 1;
ThreadSafeQueue tsq;
tsq.push(0, 0, "main");
thread t0(run, 1, "Red", ref(tsq));
thread t1(run, 2, "Green", ref(tsq));
thread t2(run, 3, "Blue", ref(tsq));
thread t3(run, 4, "Yellow", ref(tsq));
t0.join();
t1.join();
t2.join();
t3.join();
tsq.retrieveAndDelete(0, "main");
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment