Hàm pthread_equal () được sử dụng để kiểm tra xem hai luồng có bằng nhau hay không. Điều này trả về giá trị 0 hoặc khác 0. Đối với các chuỗi bằng nhau, nó sẽ trả về khác 0, nếu không thì trả về 0. Cú pháp của hàm này như dưới đây -
int pthread_equal (pthread_t th1, pthread_t th2);
Bây giờ chúng ta hãy xem pthread_equal () đang hoạt động. Trong trường hợp đầu tiên, chúng tôi sẽ kiểm tra chuỗi tự để kiểm tra kết quả.
Ví dụ
#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 will return current thread id
printf("Threads are equal\n");
} else {
printf("Threads are not equal\n");
}
}
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
} Đầu ra
Threads are equal
Bây giờ chúng ta sẽ thấy kết quả, nếu chúng ta so sánh giữa hai chuỗi khác nhau.
Ví dụ
#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 thread 1
}
void* my_thread_function2(void* p) {
if (pthread_equal(sample_thread, pthread_self())) { //pthread_self will return current thread id
printf("Threads are equal\n");
} else {
printf("Threads are not equal\n");
}
}
main() {
pthread_t th1, th2;
pthread_create(&th1, NULL, my_thread_function1, NULL); //create a thread using my_thread_function1
pthread_create(&th1, NULL, my_thread_function2, NULL); //create a thread using my_thread_function2
pthread_join(th1, NULL); //wait for joining the thread with the main thread
pthread_join(th2, NULL);
} Đầu ra
Threads are not equal