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_equal() in C
The pthread_equal() function is used to check whether two threads are equal or not. This function returns 0 if the threads are different, or a non-zero value if the threads are equal.
Syntax
int pthread_equal(pthread_t th1, pthread_t th2);
Parameters
- th1 − First thread identifier
- th2 − Second thread identifier
Return Value
Returns a non-zero value if threads are equal, otherwise returns 0.
Note: To compile and run pthread programs, use: gcc -pthread filename.c -o output
Example 1: Comparing Thread with Itself
In this example, we will check if a thread is equal to itself using pthread_self() −
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
pthread_t sample_thread;
void* my_thread_function(void* p) {
if (pthread_equal(sample_thread, pthread_self())) { /* pthread_self returns current thread id */
printf("Threads are equal<br>");
} else {
printf("Threads are not equal<br>");
}
return NULL;
}
int main() {
pthread_t th1;
sample_thread = th1; /* assign the thread th1 to another thread object */
pthread_create(&th1, NULL, my_thread_function, NULL); /* create a thread using my thread function */
pthread_join(th1, NULL); /* wait for joining the thread with the main thread */
return 0;
}
Threads are equal
Example 2: Comparing Two Different Threads
Now we will see the result when we compare between two different threads −
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
pthread_t sample_thread;
void* my_thread_function1(void* ptr) {
sample_thread = pthread_self(); /* assign the id of the current thread */
return NULL;
}
void* my_thread_function2(void* p) {
if (pthread_equal(sample_thread, pthread_self())) { /* pthread_self returns current thread id */
printf("Threads are equal<br>");
} else {
printf("Threads are not equal<br>");
}
return NULL;
}
int main() {
pthread_t th1, th2;
pthread_create(&th1, NULL, my_thread_function1, NULL); /* create a thread using my_thread_function1 */
pthread_join(th1, NULL); /* wait for first thread to complete */
pthread_create(&th2, NULL, my_thread_function2, NULL); /* create a thread using my_thread_function2 */
pthread_join(th2, NULL); /* wait for second thread to complete */
return 0;
}
Threads are not equal
Key Points
- Thread equality is determined by comparing thread identifiers, not thread functions.
- Use
pthread_self()to get the current thread's identifier. - Always include return statements in thread functions to avoid undefined behavior.
Conclusion
The pthread_equal() function provides a portable way to compare thread identifiers. It is essential for thread management and synchronization in multi-threaded applications.
Advertisements
