简体   繁体   中英

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. C++20 has the std::stop_source and std::stop_token types, which are such a communication mechanism. 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.

C++ has no mechanism to force a thread to stop; stopping a thread is something the target thread has to agree to do, and thus it has to be designed to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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