dimanche 23 avril 2017

Clean cancellation of an std::thread that is blocked on an input/output call

I have an std::thread that might be blocked on a file descriptor input/output call, how can I cleanly cancel it?

Consider the following sample:

#include <unistd.h>
#include <thread>

void thread_routine(int fd)
{
    char buf;
    read(fd, &buf, 1);
}

int main()
{
    int pipefd[2];
    pipe(pipefd);

    std::thread thread(&thread_routine, pipefd[0]);

    thread.join();

    close(pipefd[0]);
    close(pipefd[1]);
}

What can I do before the join() to be sure that it will not lock forever? (The pipe is just a quick sample way to get a file descriptor, I have a more exotic scenario but I'm trying to get a generic answer.)

With pthreads I could call pthread_cancel() because read() and write() are cancellation points, but there's no C++ way to cancel an std::thread (I could get the thread::native_handle() and pass it to pthread_cancel(), but I'd like a cleaner approach).

Please note that: - I can't set the file descriptor in non blocking mode - I can't use select() on the file descriptor

Aucun commentaire:

Enregistrer un commentaire