Cancel std :: thread with native_handle () + pthread_cancel ()

I am converting a previous thread wrapper around pthreads to std :: thread. However, C ++ 11 has no way to cancel the stream. However, I demand to cancel the threads, as they can perform a very lengthy task in an external library.

I was considering using native_handle, which gives me pthread_id in my platform. I am using gcc 4.7 on Linux (Ubuntu 12.10). The idea was as follows:

#include <iostream> #include <thread> #include <chrono> using namespace std; int main(int argc, char **argv) { cout << "Hello, world!" << endl; auto lambda = []() { cout << "ID: "<<pthread_self() <<endl; while (true) { cout << "Hello" << endl; this_thread::sleep_for(chrono::seconds(2)); } }; pthread_t id; { std::thread th(lambda); this_thread::sleep_for(chrono::seconds(1)); id = th.native_handle(); cout << id << endl; th.detach(); } cout << "cancelling ID: "<< id << endl; pthread_cancel(id); cout << "cancelled: "<< id << endl; return 0; } 

The theme is canceled by the exception thrown by pthreads.

My question is:

Will there be any problems with this approach (except that they are not portable)?

+4
source share
1 answer

No, I do not think that you will have any additional problems than:

  • not tolerated
  • you must carefully program _very_very_ to destroy all objects of the canceled stream ...

For example, the Standard says that when the end of a stream ends, the variables will be destroyed. If you cancel the thread, it will be much more difficult for the compiler, if not impossible.

I would therefore recommend not to cancel the thread if you can somehow avoid it. Write a standard polling loop, use a condition variable, listen for a signal to interrupt reading, etc. And terminate the stream regularly.

+1
source

Source: https://habr.com/ru/post/1447966/


All Articles