Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
pthread_cancel() in C
The pthread_cancel() function is used to send a cancellation request to a specific thread identified by its thread ID. This function allows one thread to request the termination of another thread in a controlled manner.
Note: To compile and run pthread programs, use: gcc -pthread filename.c -o output
Syntax
int pthread_cancel(pthread_t thread);
Parameters
- thread − The thread ID of the thread to be cancelled
Return Value
- Returns 0 on success
- Returns an error number on failure
Example: Thread Cancellation
This example demonstrates how one thread can cancel another thread after a certain condition is met −
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
int count = 0;
pthread_t sample_thread;
void* thread_one_func(void* p) {
while (1) {
printf("This is thread 1<br>");
sleep(1); /* wait for 1 second */
count++;
if (count == 5) {
/* if counter reaches 5, cancel thread 2 and exit */
printf("Thread 1: Cancelling thread 2<br>");
pthread_cancel(sample_thread);
pthread_exit(NULL);
}
}
return NULL;
}
void* thread_two_func(void* p) {
sample_thread = pthread_self(); /* store thread 2's ID */
while (1) {
printf("This is thread 2<br>");
sleep(2); /* wait for 2 seconds */
}
return NULL;
}
int main() {
pthread_t t1, t2;
/* create two threads */
pthread_create(&t1, NULL, thread_one_func, NULL);
pthread_create(&t2, NULL, thread_two_func, NULL);
/* wait for threads to complete */
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("Main thread exiting<br>");
return 0;
}
This is thread 2 This is thread 1 This is thread 1 This is thread 2 This is thread 1 This is thread 2 This is thread 1 This is thread 1 Thread 1: Cancelling thread 2 Main thread exiting
Key Points
-
pthread_cancel()only sends a cancellation request − the target thread must be in a cancellable state - Thread cancellation points include functions like
sleep(),read(),write(), etc. - Use
pthread_setcancelstate()andpthread_setcanceltype()to control cancellation behavior - Always handle thread cancellation gracefully to avoid resource leaks
Conclusion
The pthread_cancel() function provides a mechanism for cooperative thread termination. It's important to understand that cancellation is a request, not a forced termination, and proper cleanup should always be considered.
Advertisements
