相关疑难解决方法(0)

在调用condition_variable.notify_one()之前我是否必须获取锁定?

我对使用有点困惑std::condition_variable.我明白我必须创建unique_lock一个mutex调用之前condition_variable.wait().我无法找到是我是否也应该调用之前获得一个独特的锁notify_one()notify_all().

cppreference.com上的示例存在冲突.例如,notify_one页面提供了以下示例:

#include <iostream>
#include <condition_variable>
#include <thread>
#include <chrono>

std::condition_variable cv;
std::mutex cv_m;
int i = 0;
bool done = false;

void waits()
{
    std::unique_lock<std::mutex> lk(cv_m);
    std::cout << "Waiting... \n";
    cv.wait(lk, []{return i == 1;});
    std::cout << "...finished waiting. i == 1\n";
    done = true;
}

void signals()
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "Notifying...\n";
    cv.notify_one();

    std::unique_lock<std::mutex> lk(cv_m);
    i = 1;
    while (!done) {
        lk.unlock();
        std::this_thread::sleep_for(std::chrono::seconds(1)); …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading condition-variable

72
推荐指数
3
解决办法
2万
查看次数

C++ 11 std :: condition_variable:我们可以直接将锁传递给通知的线程吗?

我正在学习C++ 11并发性,其中我以前唯一的并发原语经验是六年前的操作系统类,所以如果可以,请保持温和.

在C++ 11中,我们可以编写

std::mutex m;
std::condition_variable cv;
std::queue<int> q;

void producer_thread() {
    std::unique_lock<std::mutex> lock(m);
    q.push(42);
    cv.notify_one();
}

void consumer_thread() {
    std::unique_lock<std::mutex> lock(m);
    while (q.empty()) {
        cv.wait(lock);
    }
    q.pop();
}
Run Code Online (Sandbox Code Playgroud)

这样可以正常工作,但我觉得需要包裹cv.wait一个循环.我们需要循环的原因对我来说很清楚:

Consumer (inside wait())       Producer            Vulture

release the lock
sleep until notified
                               acquire the lock
                               I MADE YOU A COOKIE
                               notify Consumer
                               release the lock
                                                   acquire the lock
                                                   NOM NOM NOM
                                                   release the lock
acquire the lock
return from wait()
HEY WHERE'S MY COOKIE                              I EATED IT
Run Code Online (Sandbox Code Playgroud)

现在,我相信其中一个很酷的事情 …

c++ concurrency multithreading condition-variable c++11

14
推荐指数
2
解决办法
6252
查看次数

c++ - 如何在运行时在c ++中停止程序3秒

我不知道如何在中间停止程序有人可以帮助我我希望我的程序停止定义的秒数,例如 3 秒或 6 秒,如果您按任意键,它会立即开始运行。

c++

5
推荐指数
1
解决办法
152
查看次数