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)?
source share