我正在尝试在之前的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
目前,下一个线程仅在前一个线程中完成工作时启动。但是我希望在前一个线程中启动工作后立即启动下一个线程,而不是等待它结束,只等待启动。
答案 0 :(得分:10)
std::async
返回std::future
保存函数执行结果。在你的情况下,它是一个临时的对象,不会被摧毁。 std::future
的文档说:
✔共享状态是通过调用std :: async
创建的✔共享状态尚未准备好
✔这是对共享状态的最后一次引用
所有这些都是正确的,因此future
的破坏将阻止,直到工作人员功能完成执行。
您可以创建分离线程以避免此问题:
std::thread(worker_thread).detach();