简体   繁体   English

是否可以终止 std::async 线程?

[英]Is it Possible to terminate the std::async thread?

I have the code below which I am calling it asynchronously for downloading a file, I want to terminate the thread?我有下面的代码,我正在异步调用它来下载文件,我想终止线程吗? How to achieive this?如何实现这一目标?

std::future<BOOL> fut = std::async(std::launch::async,&download::downloadBlob2File,&t_oftcdownload,stol(blocksize), downldUrl, token,name, path, ID);
 std::chrono::hours span (2);
 int t_iResult = -1;

 if (fut.wait_for(span)==std::future_status::timeout)
 {
  t_iResult=0;
 }

You can do it, but only in the sense that you can write the code yourself.您可以这样做,但前提是您可以自己编写代码。 You can build a mechanism to communicate to the other thread that you want it to halt, and that thread can frequently check this mechanism to see if it is being told to abort.您可以构建一种机制来与您希望它停止的其他线程进行通信,并且该线程可以经常检查此机制以查看它是否被告知要中止。

There is no mechanism built into async to help you do this. async中没有内置机制来帮助您执行此操作。 C++20 has the std::stop_source and std::stop_token types, which are such a communication mechanism. C++20 有std::stop_sourcestd::stop_token类型,它们就是这样一种通信机制。 But you have to pass a stop_token to the asynchronous function, and it must be written to manually check this mechanism periodically to see if it should stop.但是你必须给异步的function传递一个stop_token ,而且必须要定期手动检查这个机制,看它是否应该停止。

C++ has no mechanism to force a thread to stop; C++ 没有强制线程停止的机制; stopping a thread is something the target thread has to agree to do, and thus it has to be designed to do it.停止线程是目标线程必须同意做的事情,因此它必须被设计为这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM