高级别
我想在异步模式下调用一些没有返回值的函数而不等待它们完成.如果我使用std :: async,则在任务结束之前,未来的对象不会被破坏,这使得调用在我的情况下不同步.
例
void sendMail(const std::string& address, const std::string& message)
{
//sending the e-mail which takes some time...
}
myResonseType processRequest(args...)
{
//Do some processing and valuate the address and the message...
//Sending the e-mail async
auto f = std::async(std::launch::async, sendMail, address, message);
//returning the response ASAP to the client
return myResponseType;
} //<-- I'm stuck here until the async call finish to allow f to be destructed.
// gaining no benefit from the async call.
Run Code Online (Sandbox Code Playgroud)
我的问题是
我想检查一下是否std::thread已完成执行.搜索stackoverflow我发现以下问题解决了这个问题.接受的答案建议让工作线程在退出之前设置变量并让主线程检查该变量.以下是此类解决方案的最小工作示例:
#include <unistd.h>
#include <thread>
void work( bool* signal_finished ) {
sleep( 5 );
*signal_finished = true;
}
int main()
{
bool thread_finished = false;
std::thread worker(work, &thread_finished);
while ( !thread_finished ) {
// do some own work until the thread has finished ...
}
worker.join();
}
Run Code Online (Sandbox Code Playgroud)
对已接受的答案发表评论的人声称,不能使用简单的bool变量作为信号,代码在没有内存屏障的情况下被破坏并且使用std::atomic<bool>是正确的.我最初的猜测是这是错误的,简单bool就足够了,但我想确保我没有错过任何东西.以上代码是否需要a std::atomic<bool>才能正确?
假设主线程和worker正在不同套接字中的不同CPU上运行.我认为会发生的是,主线程thread_finished从其CPU的缓存中读取.当worker更新它时,缓存一致性协议负责将worker更改为全局内存并使主线程的CPU缓存无效,因此它必须从全局内存中读取更新的值.缓存一致性的全部要点是不能像上面的代码一样工作吗?
如何停止/取消使用std::async和策略创建的异步任务std::launch::async?换句话说,我已经使用future对象启动了在另一个线程上运行的任务.有没有办法取消或停止正在运行的任务?
可能重复:
有没有办法在C++ 11中取消/分离未来?
有一个成员函数使用std::future和异步运行std::async.在某些情况下,我需要取消它.(该函数连续加载对象附近,有时加载时对象超出范围.)我已经阅读了这个问题的答案,解决了同样的问题,但我不能让它工作.
这是简化的代码,其结构与我的实际程序相同.在异步运行时调用Start(),Kill()因为访问冲突而导致崩溃input.
在我看来,代码应该如下工作.当Kill()被调用时,行驶标志被禁用.下一个命令get()应该等待线程结束,它会很快检查运行标志.线程取消后,input指针将被删除.
#include <vector>
#include <future>
using namespace std;
class Class
{
future<void> task;
bool running;
int *input;
vector<int> output;
void Function()
{
for(int i = 0; i < *input; ++i)
{
if(!running) return;
output.push_back(i);
}
}
void Start()
{
input = new int(42534);
running = true;
task = async(launch::async, &Class::Function, this);
}
void Kill()
{
running = …Run Code Online (Sandbox Code Playgroud) 我有两种算法来解决任务X ().
如何为算法1启动一个线程,为算法2启动一个线程并等待第一个算法完成,之后我杀了另一个并继续?
我已经看到,join从std::thread会让我等待它完成,但我不能做join两个线程,否则我会等待既能完成.我想发布它们并等到其中一个完成.实现这一目标的最佳方法是什么?