Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cancelling std::thread using native_handle() + pthread_cancel()

I am converting a previous thread wrapper around pthreads to std::thread. However c++11 does not have any way to cancel the thread. I REQUIRE, nonetheless, to cancel threads since they may be performing a very lengthy task inside an external library.

I was considering using the native_handle that gives me pthread_id in my platform. I'm using gcc 4.7 in Linux (Ubuntu 12.10). The idea would be:

#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 thread is canceled by an exception thrown by pthreads.

My question is:

Will there be any problem with this approach (besides not being portable)?

like image 531
João Leal Avatar asked Nov 23 '12 14:11

João Leal


1 Answers

No, I don't think that you will not have additional problems than:

  • not being portable
  • having to program _very_very_ carefully that all objects of the cancelled thread are destroyed...

For example, the Standard says that when a thread ends variables will be destroyed. If you cancel a thread this will be much harder for the compiler, if not impossible.

I would, therefore recommend not to cancel a thread if you can somehow avoid it. Write a standard polling-loop, use a condition variable, listen on a signal to interrupt reads and so on -- and end the thread regularly.

like image 128
towi Avatar answered Sep 29 '22 02:09

towi