Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

terminating a thread in C

I a have a C program which calls to threads.

iret1 = pthread_create( &thread1, NULL, readdata, NULL);
iret2 = pthread_create( &thread2, NULL, timer_func, NULL);
pthread_join(thread2, NULL);

Thread 2 returns after performing some function, after which I want to stop the execution of thread 1. How should I do this?

like image 700
Vishal Avatar asked Jul 26 '11 21:07

Vishal


3 Answers

You can stop the thread using pthread_cancel:

pthread_cancel(thread1);

And in readdata:

/* call this when you are not ready to cancel the thread */
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
...
/* call this when you are ready to cancel the thread */
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

See the pthread_cancel man page for more information - there's an example included.

If you don't want to use pthread_cancel, you can use a global flag that is set by the main thread and read by thread 1. Also, you can use any of the IPC methods, like establishing a pipe between the threads.

like image 124
Antti Avatar answered Sep 20 '22 01:09

Antti


You should signal to the thread that you wish it to stop work, and then wait for it to do so. For example, you could set a boolean flag that the thread tests regularly. If that flag indicates that work has been cancelled, then the thread should return from the thread function.

Don't attempt to forcibly terminate the thread from the outside because this will leave synchronisation objects in indeterminate state, lead to deadlocks etc.

like image 33
David Heffernan Avatar answered Sep 17 '22 01:09

David Heffernan


Thread1 must have a flag which it verifies from time to time to see if it should abort itself.

There are ways to abort a thread from outside, but this is very dangerous. Don't.

Something like:

thread1stop=TRUE; //Thread 1 has access to this boolean value
pthread_join(thread1, NULL);
like image 35
André Puel Avatar answered Sep 18 '22 01:09

André Puel