Reputation: 999
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?
Upvotes: 8
Views: 37337
Reputation: 2065
tkill(tid, SIGTERM) is the call you are looking for I do believe.
Upvotes: 1
Reputation: 38270
pthread_cancel() function sends a cancellation request to the thread.
After sending the request to cancel the thread you should check the return code to confirm that the thread was actually cancelled or not.
Here is a simple example:
rc = pthread_cancel(iret2);
if(rc) printf("failed to cancel the thread\n");
For further reference:
http://cursuri.cs.pub.ro/~apc/2003/resources/pthreads/uguide/users-39.htm
Other sources which might be useful to you.
http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_create.3.html
http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_cancel.3.html
Upvotes: 0
Reputation: 12489
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.
Upvotes: 14
Reputation: 9219
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);
Upvotes: 2
Reputation: 613572
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.
Upvotes: 2