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.