20.12.31 1114. 按序打印 多线程
题目
我们提供了一个类:
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
三个不同的线程将会共用一个 Foo 实例。
线程 A 将会调用 first() 方法
线程 B 将会调用 second() 方法
线程 C 将会调用 third() 方法
请设计修改程序,以确保 second() 方法在 first() 方法之后被执行,third() 方法在 second() 方法之后被执行。
示例 1:
输入: [1,2,3]
输出: "firstsecondthird"
解释:
有三个线程会被异步启动。
输入 [1,2,3] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 second() 方法,线程 C 将会调用 third() 方法。
正确的输出是 "firstsecondthird"。
示例 2:
输入: [1,3,2]
输出: "firstsecondthird"
解释:
输入 [1,3,2] 表示线程 A 将会调用 first() 方法,线程 B 将会调用 third() 方法,线程 C 将会调用 second() 方法。
正确的输出是 "firstsecondthird"。
提示:
尽管输入中的数字似乎暗示了顺序,但是我们并不保证线程在操作系统中的调度顺序。
你看到的输入格式主要是为了确保测试的全面性。
总结
互斥锁
- lock_guard使用了RAII,构造函数上锁,析构函数解锁,即退出函数体时会自动解锁
- unique_lock更灵活
- 构造函数第二个参数可以是构造前已经上锁
adopt_lock
,推迟上锁defer_lock
,构造时尝试上锁try_to_lock
,不加参数直接上锁 - 成员函数有lock,unlock,try_lock
- 有和lock_guard相同的RAII
- 构造函数第二个参数可以是构造前已经上锁
- 都需要声明一个mutex,利用其进行初始化
条件变量
condition_variable
要和unique_lock
配套使用wait
不满足条件时会unlock然后block,当被notify的时候先lock起来,再判断条件;若为真,往下执行,若为假,unlcok & blcok- notify_all通知所有wait的线程,notify_one通知某个wait的线程
代码
//互斥锁
class Foo {
public:
mutex mtx1, mtx2;
unique_lock<mutex> lock1, lock2;
Foo():lock1(mtx1, try_to_lock), lock2(mtx2, try_to_lock) {
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
lock1.unlock();
}
void second(function<void()> printSecond) {
lock_guard<mutex> lg1(mtx1);
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
lock2.unlock();
}
void third(function<void()> printThird) {
lock_guard<mutex> lg2(mtx2);
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
};
//条件变量
class Foo {
public:
mutex mtx;
int rec = 0;
condition_variable cv;
Foo() {
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
rec = 1;
cv.notify_all();
}
void second(function<void()> printSecond) {
unique_lock<mutex> ulmtx(mtx);
cv.wait(ulmtx, [this](){return rec == 1;});
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
rec = 2;
cv.notify_one();
}
void third(function<void()> printThird) {
unique_lock<mutex> ulmtx(mtx);
cv.wait(ulmtx, [this](){return rec == 2;});
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
};