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