How do I force a Posix thread to terminate after a specified time?
I want the Posix thread to exit after a certain amount of time has passed. You can see my solution in simple C ++ Python pseudocode. But I don't think this is an effective and accurate solution. What's the best way to accomplish this?
Mutex incrementLock
BigInteger n = 0
int milliToWork = 5000
Worker()
int elapsedMilli = 0
while elapsedMilli < milliToWork
clock_t startClock = clock()
Lock(incrementLock)
n += 1
Unlock(incrementLock)
clock_t endClock = clock()
elapsedMilli += (double)(endClock - startClock) / (double)CLOCKS_PER_SEC * 1000.0
main()
int nThreads = 100
Thread threads[nThreads]
for i = 1 to nThreads
ThreadCreate(threads[i], Worker)
for i = 1 to nThreads
ThreadJoin(threads[i])
+3
source to share
1 answer
You can set up a timer to send you an alarm when your time. Pseudocode:
sig_action_handler()
{
/*cleanup*/
pthread_exit();
}
worker()
{
sigaction(sig_action_handler);
timer_create();
timer_settime();
while(true)
{
/*do work*/
}
}
Alternatively and to simplify streams:
sig_action_handler(int, siginfo_t *t, void *)
{
volatile sig_atomic_t *at = t->si_value.sival_ptr;
*at = true;
}
worker()
{
volatile sig_atomic_t at = 0;
struct sigevent si = {/*...*/, .sigev_value.sival_ptr = &at};
sigaction(sig_action_handler);
timer_create(/*...*/, &si, /*...*/);
timer_settime();
while(!at)
{
/*do work*/
}
/*cleanup*/
}
0
source to share