Suppose we have a class:
public class Foo {
public void first() { print("first"); }
public void second() { print("second"); }
public void third() { print("third"); }
}
The same instance of Foo will be passed to three different threads. Thread A will call first(), thread B will call second(), and thread C will call third(). Design a mechanism and modify the program to ensure that second() is executed after first(), and third() is executed after second().
Example 1:
Input: [1,2,3]
Output: "firstsecondthird"
Explanation: There are three threads being fired asynchronously. The input [1,2,3] means thread A calls first(), thread B calls second(), and thread C calls third(). "firstsecondthird" is the correct output.
Example 2:
Input: [1,3,2]
Output: "firstsecondthird"
Explanation: The input [1,3,2] means thread A calls first(), thread B calls third(), and thread C calls second(). "firstsecondthird" is the correct output.
Note:
We do not know how the threads will be scheduled in the operating system, even though the numbers in the input seems to imply the ordering. The input format you see is mainly to ensure our tests' comprehensiveness.
LeetCode上一道简单的多线程题目,可以看成是人和房间的关系,每个线程相当于一个人,执行代码需要进入到房间。三个线程同步需要两把锁。可以使用std::mutex, 第一个人可以直接进入房间,而第二个人进入房间需要一把锁,第三个人进入房间需要两把锁。代码如下:
class Foo {
private:
mutex m1,m2;
public:
Foo() {
m1.lock();
m2.lock();
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
m1.unlock();
}
void second(function<void()> printSecond) {
m1.lock();
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
m1.unlock();
m2.unlock();
}
void third(function<void()> printThird) {
m2.lock();
// printThird() outputs "third". Do not change or remove this line.
printThird();
m2.unlock();
}
};
此外除了lock()和unlock()执行操作,更好的办法是采用RAII方法来加锁解锁,避免在临界区中因为抛出异常或return等操作导致没有解锁就退出的问题。C++11中提供了std::lock_guard类模板
class Foo {
private:
mutex m1,m2;
public:
Foo() {
m1.lock();
m2.lock();
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
m1.unlock();
}
void second(function<void()> printSecond) {
lock_guard<mutex> lk(m1);
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
m2.unlock();
}
void third(function<void()> printThird) {
lock_guard<mutex> lc(m2);
lock_guard<mutex> ld(m1);
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
};