Possible Duplicate:
kill thread in pthread
Here after a source code containing a launch of thread and then after a while I want to kill it. How to do it ? Without make any change in the thread function
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
pthread_t test_thread;
void *thread_test_run (void *v) // I must not modify this function
{
int i=1;
while(1)
{
printf("into thread %d\r\n",i);
i++;
sleep(1);
}
return NULL
}
int main()
{
pthread_create(&test_thread, NULL, &thread_test_run, NULL);
sleep (20);
// Kill the thread here. How to do it?
// other function are called here...
return 0;
}
You can use pthread_cancel() to kill a thread:
Note that the thread might not get a chance to do necessary cleanups, for example, release a lock, free memory and so on..So you should first use
pthread_cleanup_push()to add cleanup functions that will be called when the thread is cancelled. From man pthread_cleanup_push(3):Regarding the question of whether a thread will be cancelled if blocking or not, it’s not guaranteed, note that the manual also mentions this:
So this means that the only guaranteed behaviour is the the thread will be cancelled at a certain point after the call to
pthread_cancel().Note:
If you cannot change the thread code to add the cleanup handlers, then your only other choice is to kill the thread with pthread_kill(), however this is a very bad way to do it for the aforementioned reasons.