How do you make function foo() run for only a period of time? I think threads is the most common way of impementation.
How do I use bind and timed_join ??
How do you make function foo() run for only a period of time? I think threads is the most common way of impementation.
How do I use bind and timed_join ??
Code is not at war with other code. Code cooperates to get the job done. If you only want foo
to run for a minute, code it to only run for a minute. Don't code it some other way and then try to force it to work some way other than the way it was coded.
If you want to use threads, you can code foo
to check a synchronized "abort" flag. If foo
notices the flag is set, it aborts. Then, after a minute, set that flag from another thread. Then foo
will notice the flag is set and abort itself.
If you need to abort things like blocking I/O operations, the solutions are platform-specific. Or you can use a portable library that provides such capabilities, such as Boost.
I'm not exactly sure what your are asking. If you just need a function to do something for a minute, can you just wrap it in a while loop?
void foo(void)
{
time_t end = time(NULL) + 60;
while (time(NULL) <= end)
{
… // do something
}
}
How do you make function foo() run for only a period of time?
The POSIX pthread
APIs support cancellation, but immediate cancellation is not guaranteed by the standard. But below is an illustration of how it might be used to cancel a function foo
after 1 second when it would normally run for 5 seconds.
void foo ()
{
sleep(5);
}
void * start_foo (void *)
{
int x;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &x);
foo();
return 0;
}
pthread_t t;
pthread_create(&t, 0, start_foo, 0);
sleep(1);
pthread_cancel(t);
pthread_join(t, 0);
The start_foo
function enables the cancellation state. The x
parameter receives the old cancellation state.
How do I use bind and timed_join ??
I believe you are referring to boost::bind
and boost::thread::timed_join
. boost::bind
provides a mechanism to define a functor that doesn't take any arguments, but calls a function that is passed an argument. boost::thread
requires a functor that doesn't take an argument, so that is why it is used there.
boost::thread t(boost::bind(puts, "hello, world"));
boost::thread::timed_join
is a join on the boost::thread
that may return false if the thread has not finished within the time parameter passed to it.
boost::thread t(foo);
t.timed_join(boost::posix_time::seconds(1));