代码之家  ›  专栏  ›  技术社区  ›  Alessandro Picardi

多线程操作

  •  0
  • Alessandro Picardi  · 技术社区  · 8 年前

    我有这个多线程的练习要解决。我必须创建一个类,其中5个线程相互等待,当第五个线程到达时,它们都是解锁的。 我用add()方法创建了一个类,该方法将variableX增加1,创建了一个线程,该线程接收print()函数,然后再连接它。函数print()检查variableX是否小于5,如果是条件变量wait,否则条件变量用notify_all()函数唤醒所有线程。编译器给出0个错误,但通过调试,我发现程序陷入了死锁。这是一个片段

    #include "stdafx.h"
    #include <iostream>
    #include <thread>
    #include <mutex>
    #include <condition_variable>
    using namespace std;
    
    void print(mutex & mtx, condition_variable & convar, int x) {
        if (x < 5){
            unique_lock<mutex> lock(mtx); //acquire and lock the mutex
            convar.wait(lock); //unlock mutex and wait
        }
        else {
            convar.notify_all();
            cout << "asdasd" << endl;
        }
    }
    
    class foo {
    public:
        void add() {
            this->x = x + 1;
            thread t1(print, ref(mtx), ref(cv), x);
            t1.join();
        }
    
    private:
        mutex mtx;
        condition_variable cv;
        int x;
    };
    
    int main() {
        foo f;
        f.add();
        f.add();
        f.add();
        f.add();
        f.add();
    }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Swordfish    8 年前

    你的职能

    void add() {
        this->x = x + 1;
        thread t1(print, ref(mtx), ref(cv), x);
        t1.join();
    }
    

    创建一个线程,然后等待( join() )直到线结束。因为你的线程函数

    void print(mutex & mtx, condition_variable & convar, int x) {
        if (x < 5){
            unique_lock<mutex> lock(mtx);
            convar.wait(lock); // waits if x < 5
        }
        // ...
    

    x 可能是(您没有初始化它)<5您的死锁。

    #include <iostream>
    #include <thread>
    #include <mutex>
    #include <vector>
    #include <condition_variable>
    using namespace std;
    
    void print(mutex & mtx, condition_variable & convar, int x)
    {
        if (x < 5) {
            unique_lock<mutex> lock{ mtx };
            convar.wait(lock);
        } else {
            convar.notify_all();
            cout << "asdasd\n";
        }
    }
    
    class foo {
    private:
        mutex mtx;
        condition_variable cv;
        int x{ 0 };
        std::vector<thread> threads;
    public:
        void add() {
            ++x;
            threads.push_back(thread(print, ref(mtx), ref(cv), x));
        }
    
        ~foo() {
            for (auto &t : threads)
                t.join();
        }
    };
    
    int main() {
        foo f;
        f.add();
        f.add();
        f.add();
        f.add();
        f.add();
    }