簡體   English   中英

測試隊列中等待condition_variables的多個線程

[英]Testing multiple threads waiting on condition_variables in a queue

我正在測試如何在隊列中推送等待condition_variables的對象。 我想按我的意願執行線程,因為它們將在稍后的關鍵部分中介紹。 線程沒有打印任何內容,這可能是什么問題?

mutex print_mu;

void print(function<void()> func)
{
    lock_guard<mutex> lock(print_mu);
    func();
}

unsigned int generate_id()
{
    static unsigned int id = 1;
    return id++;
}

class foo
{
    unsigned int id_;
    mutex mu_;
    condition_variable cv_;
    bool signal_;
    bool& kill_;
public:
    foo(bool kill) 
        :kill_(kill) 
        , signal_(false)
        , id_(generate_id())
    {
        run();
    }

    void set()
    {
        signal_ = true;
    }

    void run()
    {
        async(launch::async, [=]()
        {
            unique_lock<mutex> lock(mu_);
            cv_.wait(lock, [&]() { return signal_ || kill_ ; });

            if (kill_)
            {
                print([=](){ cout << " Thread " << id_ << " killed!" << endl; });
                return;
            }

            print([=](){ cout << " Hello from thread " << id_ << endl; });
        });
    }
};

int main()
{
    queue<shared_ptr<foo>> foos;
    bool kill = false;

    for (int i = 1; i <= 10; i++)
    {
        shared_ptr<foo> p = make_shared<foo>(kill);
        foos.push(p);
    }
    this_thread::sleep_for(chrono::seconds(2));

    auto p1 = foos.front();
    p1->set();
    foos.pop();

    auto p2 = foos.front();
    p2->set();
    foos.pop();

    this_thread::sleep_for(chrono::seconds(2));

    kill = true; // terminate all waiting threads unconditionally

    this_thread::sleep_for(chrono::seconds(2));

    print([=](){ cout << " Main thread exits" << endl; });

    return 0;
}

當一個線程調用std::condition_variable::wait ,它將阻塞,直到另一個線程在相同的condition_variable上調用notify_onenotify_all為止。 由於您永遠不會在任何condition_variables上調用notify_* ,因此它們將永遠被阻止。

您的foo::run方法也將永遠阻塞,因為std::future的析構函數將阻塞等待std::async調用的結果,如果它是最后引用該結果的std::future 因此,您的代碼陷入僵局:主線程被阻塞,等待異步將來完成,而異步將來被阻塞,等待主線程發出cv_信號。

(也foo::kill_是一個懸空的引用。嗯,如果無論如何返回run ,它將成為一個。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM