Re: [閒聊] 每日LeetCode已回收

看板Marginalman作者 (ヰ世界情緒的魚)時間3年前 (2022/11/09 21:47), 編輯推噓1(104)
留言5則, 4人參與, 3年前最新討論串94/719 (看更多)
沒事來練習一下 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(); } }; -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.228.96.239 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1668001675.A.AF0.html

11/09 21:49, 3年前 , 1F
大師
11/09 21:49, 1F

11/09 21:49, 3年前 , 2F
我覺得thread寫得好的人都很厲害
11/09 21:49, 2F

11/09 21:51, 3年前 , 3F
我不會寫 現在才會在這邊練 太苦了
11/09 21:51, 3F

11/09 21:52, 3年前 , 4F
原來LEETCODE有THREAD的題目 題目少到我沒發現有
11/09 21:52, 4F

11/09 23:48, 3年前 , 5F
大師
11/09 23:48, 5F
文章代碼(AID): #1ZQw-Bhm (Marginalman)
討論串 (同標題文章)
文章代碼(AID): #1ZQw-Bhm (Marginalman)