需要帮助识别简单多线程代码中的错误

Need Help Identifying Bug in Simple Multithreaded Code

本文关键字:代码 错误 多线程 简单 帮助 识别      更新时间:2023-10-16

我试图解决这里给出的问题 - https://leetcode.com/problems/print-foobar-alternately/。

我编写了以下代码来解决问题,但它超过了分配的时间限制。我不明白为什么会这样。有人可以指出我的错误吗?另外,我如何更正下面给出的代码,使其在仅使用 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;
        }
    }
};

虽然循环不是锁。锁只允许一个线程通过。在你的代码中,如果 state=0,两个线程可能会一个接一个地打印 foo。要解决此问题,请使用互斥锁和唯一锁。


 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;
        }

切勿跨线程读取相同的变量,除非将其设置为原子或修改锁中的变量。在此示例中,由于值状态在共享互斥锁中正在更改,因此无需使用原子。