pthread_equal()函數用于檢查兩個線程是否相等。它返回0或非零值。對于相等的線程,它將返回非零值,否則返回0。該函數的語法如下:
int pthread_equal (pthread_t th1, pthread_t th2);
登錄后復制
現在讓我們看看 pthread_equal() 的實際作用。第一種情況,我們會檢查自線程來檢查結果。
示例
#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"); } else { printf("Threads are not equal
"); } } 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 }
登錄后復制
輸出
Threads are equal
登錄后復制
現在,如果我們在兩個不同的線程之間進行比較,我們將看到結果。
示例
#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"); } else { printf("Threads are not equal
"); } } 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); }
登錄后復制
輸出
Threads are not equal
登錄后復制
以上就是在C語言中,pthread_equal()函數用于比較兩個線程ID是否相等的詳細內容,更多請關注www.xfxf.net其它相關文章!