user1032861
user1032861

Reputation: 527

How can I timeout a thread on linux?

On Linux, using C, I'm trying to launch several threads (pthreads) and I want them to be killed if they don't finish after X seconds. How do I suggest I do this? My first thought is to use POSIX timers and a list to set the timer to the next one and kill the respective thread. It should work, but there should be a simpler way to implement this. Any idea? :)

Upvotes: 0

Views: 7466

Answers (2)

jcfaracco
jcfaracco

Reputation: 894

Here, a simple sample taken from http://www.cs.cf.ac.uk/Dave/C/node31.html

#include <pthread.h> 
#include <time.h> 

pthread_timestruc_t to;
pthread_cond_t cv; 
pthread_mutex_t m;
timestruct_t abstime; 
int ret; 

/* wait on condition variable */ 

ret = pthread_cond_timedwait(&cv, &m, &abstime);

pthread_mutex_lock(&m); 
/* initialize time variable */
to.tv_sec = time(NULL) + TIMEOUT; 
to.tv_nsec = 0; 

while (cond == FALSE) 
 {  err = pthread_cond_timedwait(&c, &m, &to); 
    if (err == ETIMEDOUT) 
       { /* timeout, do something */ 
       break; 
    } 
 }
pthread_mutex_unlock(&m);

You can set the timeout defining the TIMEOUT macro in seconds.

Upvotes: 2

Duck
Duck

Reputation: 27542

First, put it out of your mind that there is a "simple" way to kill threads. Any sufficiently useful thread is going to hold resources - file descriptors, buffers, pointers to heap allocated memory, locks, condvars, etc. Just sending a "bang you're dead" signal is seldom the right thing to do for anything but the most trivial program.

That said there are two main things you have to consider: the thread shutdown method and the timers.

It terms of shutdown there are several possibilities: (1) sending a signal to kill the thread (usually bad); (2) alerting the thread to shut itself down via some method (e.g. a pipe read, setting a switch in the threads event loop, a non-fatal signal, etc; (3) the pthread_cancel mechanism.

The timer options pretty much lead you to the timer_create family of calls. If you plan on timing and canceling multiple threads then you need multiple timers and alarm and itimer aren't going to cut it. timer_create allows you multiple options. You can direct the emitted signal at the thread(s) you want to cancel or a monitoring thread which then cancels the overdue thread. If you read through the documentation you can see some of the possibilities but which is right for your situation only you can know right now.

Upvotes: 2

Related Questions