Reputation: 6168
I want to add a feature in my project.
I have 2 functions running in a for-loop because I want to find the solution of the functions in random arrays. I also have an function that makes random arrays. In each loop the array that is made by the random_array fun are the input of the 2 functions. The 2 functions print solutions in the screen , they dont return an argument.
int main(){
for (i=0;i<50 i++)
{
arr1=ramdom_array();
func1(arr1)
func2(arr1)
}
}
I need to stop the functions running if they have not ended in 5 minutes. I have thought that I have to put in the functions something like this :
void func1(array<array<int,4>,4> initial)
{
while (5minutes_not_passed)
{
//do staff
if(solution==true)
break;
}
}
But I dont know what to put in the 5minutes_not_passed.
the declaration of the functions are like this:
void func1(array<array<int,4>,4> initial)
void func2(array<array<int,4>,4> initial)
I have found that I can use the thread library but I dont think meshing up with threads in a good idea. I believe something like a timer is needed. Note that the functions sometimes might end before 5 minutes.
Upvotes: 1
Views: 2848
Reputation: 478
Or maybe you can use something like kevents (freebsd) which has a timer notification and Signal handling would do the trick too. http://www.linuxquestions.org/questions/programming-9/how-to-use-sigusr1-and-sigusr2-391489/
So,after a timeout, you would need to send a SIGUSR1 to your process,and then in the signal handler function,you could have your logic for exiting.
Upvotes: 0
Reputation: 1161
I know you said you don't want to use threads, but boost::thread would make this really easy.
boost::thread t(boost::bind(func1, arr1));
if(!t1.timed_join(boost::posix_time::minutes(5))){
// thread still running, use interrupt or detach
}
Upvotes: 0
Reputation: 6814
I would recommend executing your function in a thread with a timeout. Here's a link to a similar asked question:
C++: How to implement a timeout for an arbitrary function call?
Upvotes: 0
Reputation: 28837
Use time_t and time to get the current second.
add 5 * 60 to that value.
in every iteration of the loop, get the time, and if it is greater than or equal to your limit, break out
Upvotes: 3