我們提供了一個類:
public class Foo {
public void one() { print("one"); }
public void two() { print("two"); }
public void three() { print("three"); }
}
三個不同的線程將會共用一個 Foo 實例。
線程 A 將會調用 one() 方法
線程 B 將會調用 two() 方法
線程 C 將會調用 three() 方法
請設計修改程序,以確保 two() 方法在 one() 方法之後被執行,three() 方法在 two() 方法之後被執行。
示例 1:
輸入: [1,2,3]
輸出: "onetwothree"
解釋:
有三個線程會被異步啓動。
輸入 [1,2,3] 表示線程 A 將會調用 one() 方法,線程 B 將會調用 two() 方法,線程 C 將會調用 three() 方法。
正確的輸出是 "onetwothree"。
示例 2:
輸入: [1,3,2]
輸出: "onetwothree"
解釋:
輸入 [1,3,2] 表示線程 A 將會調用 one() 方法,線程 B 將會調用 three() 方法,線程 C 將會調用 two() 方法。
正確的輸出是 "onetwothree"。
注意:
儘管輸入中的數字似乎暗示了順序,但是我們並不保證線程在操作系統中的調度順序。
你看到的輸入格式主要是爲了確保測試的全面性。
class Foo {
public:
Foo() {
}
void first(function<void()> printFirst) {
// 等待直至 main() 發送數據
std::unique_lock<std::mutex> lk(g_mutex);
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
// 通知前完成手動解鎖,以避免等待線程才被喚醒就阻塞(細節見 notify_one )
counter++;
cv1.notify_one();
}
void second(function<void()> printSecond) {
std::unique_lock<std::mutex> lk(g_mutex);
cv1.wait(lk, [this](){return counter == 2;}); // 阻塞當前線程,直到條件變量被喚醒
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
counter++;
cv2.notify_one();
}
void third(function<void()> printThird) {
std::unique_lock<std::mutex> lk(g_mutex);
cv2.wait(lk, [this](){return counter == 3;});
// printThird() outputs "third". Do not change or remove this line.
printThird();
}
private:
int counter = 1;
std::condition_variable cv1;
std::condition_variable cv2;
// 使用lock和unlock手動加鎖
std::mutex g_mutex;
};
作者:georgeC
鏈接:https://leetcode-cn.com/problems/print-in-order/solution/cpp-beats-100-shi-yong-tiao-jian-bian-liang-by-geo/