views:

66

answers:

1

I'm trying to implement a program which runs a function limited by a fixed amount of time. I've managed to do it with pthreads but I would like to use Boost::thread. So far I've coded the following:

#include <boost/thread.hpp>
#include <unistd.h>
#include <signal.h>

#include <iostream>

using namespace std;

boost::thread mythread;

void third_party(){
    std::cout << "hello world" << std::endl;
}
void func (){
    while (1){
        third_party();
        boost::this_thread::interruption_point();
    }
}
void finish(int id){
    mythread.interrupt();
}

int main (){

    mythread = boost::thread(func);

    signal(SIGALRM, finish);
    alarm(2);

    mythread.join();

    return 0;
}

I set an alarm that goes off after 2 seconds and call finish, that will interrupt mythread. The problem is that func will only stop after reaching the interruption checkpoint. In the actual case I want to use this, third_party (to which code I don't have acess) could take a great amount of time and I don't want to wait until it reaches boost::this_thread::interruption_point().

I'm wondering if I can achieve this with Boost::thread or even a simpler way to do the mentioned task.

+2  A: 

Boost does not provide a method to do interruptions immeadiately, but they do provide a way to get the native thread handle, so if your native threading library supports immeadiate interrupts, then you can still utilize that method.

Look at boost::thread::native_handle() to get access the the native handle.

It might be a good idea to create your own thread class that provides the extended funtionality that you need that derives from the boost::thread class.

diverscuba23
It should be noted that some of the operating systems `boost::thread` supports do not support instant interruption like this either. And for those that do, terminating the thread won't allow that thread's stack to be unwound or allow that thread to cleanly destroy it's data. One should probably use `interruption_point` instead even if the platform provides instant interruption for these reasons.
Billy ONeal