[英]Need Help Identifying Bug in Simple Multithreaded Code
I was trying to solve the problem given here - https://leetcode.com/problems/print-foobar-alternately/ . 我试图解决此处给出的问题-https: //leetcode.com/problems/print-foobar-alternately/ 。
I wrote the following code to solve the problem but it exceeds the alloted time limit. 我编写了以下代码来解决该问题,但它超出了分配的时间限制。 I am not able to understand why that is the case. 我不明白为什么会这样。 Can someone please point out my mistake ? 有人可以指出我的错误吗? Also, how can I correct the code given below so that it executes faster while using only while loops to act as a mutex ? 另外,如何纠正下面给出的代码,以便仅使用while循环充当互斥体时执行速度更快?
class FooBar {
private:
int n;
int state = 0;
public:
FooBar(int n) {
this->n = n;
state = 0;
}
void foo(function<void()> printFoo) {
for (int i = 0; i < n; i++) {
// printFoo() outputs "foo". Do not change or remove this line.
while(state == 1);
printFoo();
state = 1;
}
}
void bar(function<void()> printBar) {
for (int i = 0; i < n; i++) {
// printBar() outputs "bar". Do not change or remove this line.
while(state == 0);
printBar();
state = 0;
}
}
};
While loops aren't locks. 虽然循环不是锁。 Locks only allow one thread to pass. 锁只允许一个线程通过。 In your code if state=0 two threads may print foo one after the another. 在您的代码中,如果state = 0,则两个线程可能一个接一个地打印foo。 To solve this problem use a mutex and a unique lock. 要解决此问题,请使用互斥锁和唯一锁。
for (int i = 0; i < n; i++) {
// printFoo() outputs "foo". Do not change or remove this line.
while(state==1);
unique_lock<mutex> lck(m1); //Make mutex m1 as a global mutex
printFoo();
state = 1;
}
Never read the same variable across threads withouth making it atomic or modifying the variable within a lock. 切勿跨线程读取同一变量,除非使其成为原子变量或修改锁中的变量。 In this example since the value state is changing within a shared mutex you don't need to use atomic. 在此示例中,由于值状态在共享互斥锁内更改,因此您无需使用atomic。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.