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

时间:2019-07-12 23:22:29

标签: c++ multithreading concurrency

我正在尝试解决此处给出的问题-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;
        }
    }
};

1 个答案:

答案 0 :(得分: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;
        }

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