ホームページ  >  記事  >  バックエンド開発  >  C 言語では、pthread_equal() 関数を使用して、2 つのスレッド ID が等しいかどうかを比較します。

C 言語では、pthread_equal() 関数を使用して、2 つのスレッド ID が等しいかどうかを比較します。

WBOY
WBOY転載
2023-09-22 16:29:021144ブラウズ

C 言語では、pthread_equal() 関数を使用して、2 つのスレッド ID が等しいかどうかを比較します。

pthread_equal() 関数は、2 つのスレッドが等しいかどうかを確認するために使用されます。 0 またはゼロ以外の値を返します。スレッドが等しい場合は 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

次に、2 つの異なるスレッド間を比較すると、結果がわかります。

#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() 関数を使用して、2 つのスレッド ID が等しいかどうかを比較します。の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はtutorialspoint.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。