Re: [閒聊] 每日LeetCode

作者: argorok (s.green)   2022-11-09 21:47:53
沒事來練習一下 concurrency的題目
1114. Print in Order
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().
Note:
We do not know how the threads will be scheduled in the operating system, even
though the numbers in the input seem to imply the ordering. The input format
you see is mainly to ensure our tests' comprehensiveness.
Input: nums = [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.
題目要求很簡單 數字表示thread執行順序
反正不管怎樣的執行順序 就是要照 firstsecondthird的順序
解題思路就是用一個數字表示順序+condition variable去判斷現在要印誰
wait裡面lambda要記得加& or this 去抓class變數
cv.wait會一直等待直到數字符合 所以印完一個就改數字+提醒其他function去檢查
就醬
以下解答
#include <mutex>
#include <condition_variable>
class Foo {
private:
std::mutex m;
std::condition_variable cv;
int turn = 0;
public:
Foo() {
}
void first(function<void()> printFirst) {
std::unique_lock<mutex> lock(m);
cv.wait(lock, [&]{return turn == 0;});
// printFirst() outputs "first". Do not change or remove this line.
printFirst();
turn = 1;
cv.notify_all();
}
void second(function<void()> printSecond) {
std::unique_lock<mutex> lock(m);
cv.wait(lock, [&]{return turn == 1;});
// printSecond() outputs "second". Do not change or remove this line.
printSecond();
turn = 2;
cv.notify_all();
}
void third(function<void()> printThird) {
std::unique_lock<mutex> lock(m);
cv.wait(lock, [&]{return turn == 2;});
// printThird() outputs "third". Do not change or remove this line.
printThird();
turn = 0;
cv.notify_all();
}
};
作者: Jaka (Jaka)   2022-11-09 21:49:00
大師我覺得thread寫得好的人都很厲害
作者: argorok (s.green)   2022-11-09 21:51:00
我不會寫 現在才會在這邊練 太苦了
作者: Rushia (みけねこ的鼻屎)   2022-11-09 21:52:00
原來LEETCODE有THREAD的題目 題目少到我沒發現有

Links booklink

Contact Us: admin [ a t ] ucptt.com