首頁  >  文章  >  後端開發  >  在C語言中,pthread_equal()函數用來比較兩個執行緒ID是否相等

在C語言中,pthread_equal()函數用來比較兩個執行緒ID是否相等

WBOY
WBOY轉載
2023-09-22 16:29:021142瀏覽

在C語言中,pthread_equal()函數用來比較兩個執行緒ID是否相等

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</p><p>");
   } else {
      printf("Threads are not equal</p><p>");
   }
}
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</p><p>");
   } else {
      printf("Threads are not equal</p><p>");
   }
}

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是否相等的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除