gpt4 book ai didi

c++条件变量通知未按预期工作

转载 作者:可可西里 更新时间:2023-11-01 15:16:53 25 4
gpt4 key购买 nike

我正在尝试在之前的 worker_thread 中的工作开始 后立即启动新线程,但可能已经结束也可能没有。我用时间延迟替换了开始和结束的工作。我的代码是:

#include <iostream>
#include <string>
#include <mutex>
#include <condition_variable>
#include <future>
#include <atomic>
#include <chrono>
#include <thread>

std::mutex m;
std::condition_variable cv;
bool started = false;

void worker_thread()
{
std::unique_lock<std::mutex> lk(m);

static std::atomic<int> count(1);
std::this_thread::sleep_for(std::chrono::milliseconds{(count % 5) * 100});
std::cerr << "Start Worker thread: " << count << "\n";

started = true;
lk.unlock();
cv.notify_one();

std::this_thread::sleep_for(std::chrono::milliseconds{3000});
std::cerr << "Exit Worker thread: " << count << "\n";
++count;
}

int main()
{
while(1) {
std::async(std::launch::async, worker_thread);
std::unique_lock<std::mutex> lk(m);
cv.wait(lk, []{return started;});
started = false;
}
}

输出看起来像这样:

Start Worker thread: 1
Exit Worker thread: 1
Start Worker thread: 2
Exit Worker thread: 2
Start Worker thread: 3
Exit Worker thread: 3
Start Worker thread: 4
Exit Worker thread: 4
Start Worker thread: 5
Exit Worker thread: 5

这不是我想要的行为。我想要的是(不完全是)这样的东西:

Start Worker thread: 1
Start Worker thread: 2
Start Worker thread: 3
Start Worker thread: 4
Exit Worker thread: 1
Exit Worker thread: 3
Exit Worker thread: 4
Exit Worker thread: 2
Start Worker thread: 5
Exit Worker thread: 5

目前下一个线程只有在前一个线程的工作完成后才会启动。但是我想在上一个线程开始工作后立即启动下一个线程,而不是等待它结束,只等待开始。

最佳答案

std::async 返回一个 std::future 保存函数执行的结果。在您的情况下,它是一个被立即销毁的临时对象。 std::future 的文档说:

these actions will not block for the shared state to become ready, except that it may block if all of the following are true:

✔ the shared state was created by a call to std::async

✔ the shared state is not yet ready

✔ this was the last reference to the shared state

所有这些都是正确的,因此对 future 的破坏将阻塞,直到 worker 函数完成执行。

你可以创建分离线程来避免这个问题:

std::thread(worker_thread).detach();

关于c++条件变量通知未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43156908/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com