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.
这题主要让我们把并行执行的三个函数按顺序执行打印的语句。这里直接使用条件变量即可,第一次唤醒所有,第二次唤醒最后一个即可。主要注意锁的释放。
class Foo {
public:
Foo() {
step = 0;
}
void first(function<void()> printFirst) {
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
{
std::unique_lock<std::mutex> ul(lk);
step = 1;
}
cv.notify_all();
}
void second(function<void()> printSecond) {
{
std::unique_lock<std::mutex> ul(lk);
cv.wait(ul, [this]() {return this->step == 1;});
}
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
{
std::unique_lock<std::mutex> ul(lk);
step = 2;
}
cv.notify_one();
}
void third(function<void()> printThird) {
{
std::unique_lock<std::mutex> ul(lk);
cv.wait(ul, [this]() -> bool {return this->step == 2;});
}
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
int step;
std::mutex lk;
std::condition_variable cv;
};