Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a running thread? [duplicate]

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;
}
like image 599
MOHAMED Avatar asked Dec 04 '22 13:12

MOHAMED


2 Answers

You can use pthread_cancel() to kill a thread:

int pthread_cancel(pthread_t 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):

These functions manipulate the calling thread's stack of thread-cancellation clean-up handlers. A clean-up handler is a function that is automatically executed when a thread is cancelled (or in various other circumstances described below); it might, for example, unlock a mutex so that it becomes available to other threads in the process.

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:

A thread's cancellation type, determined by pthread_setcanceltype(3), may be either asynchronous or deferred (the default for new threads). Asynchronous cancelability means that the thread can be canceled at any time (usually immediately, but the system does not guarantee this). Deferred cancelability means that cancellation will be delayed until the thread next calls a function that is a cancellation point.

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.

like image 177
iabdalkader Avatar answered Jan 04 '23 15:01

iabdalkader


The short answer is this: With the cooperation of the code that thread is running, you may terminate it using any method it supports. Without the cooperation of the code that thread is running, you shouldn't even try it. What if the thread is holding a critical lock when you kill it? What if the thread has allocated memory and there is no other code to free that memory?

like image 40
David Schwartz Avatar answered Jan 04 '23 17:01

David Schwartz