pthread_equal()函數(shù)用于檢查兩個(gè)線程是否相等。它返回0或非零值。對(duì)于相等的線程,它將返回非零值,否則返回0。該函數(shù)的語(yǔ)法如下:
int pthread_equal (pthread_t th1, pthread_t th2);
登錄后復(fù)制
現(xiàn)在讓我們看看 pthread_equal() 的實(shí)際作用。第一種情況,我們會(huì)檢查自線程來(lái)檢查結(jié)果。
示例
#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 }
登錄后復(fù)制
輸出
Threads are equal
登錄后復(fù)制
現(xiàn)在,如果我們?cè)趦蓚€(gè)不同的線程之間進(jìn)行比較,我們將看到結(jié)果。
示例
#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); }
登錄后復(fù)制
輸出
Threads are not equal
登錄后復(fù)制
以上就是在C語(yǔ)言中,pthread_equal()函數(shù)用于比較兩個(gè)線程ID是否相等的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.xfxf.net其它相關(guān)文章!