开发者

Instantaneous interruption of a Boost::thread

开发者 https://www.devze.com 2023-01-14 08:12 出处:网络
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

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.


Boost does not provide a method to do interruptions immediately, but they do provide a way to get the native thread handle, so if your native threading library supports immediate 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 functionality that you need that derives from the boost::thread class.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号