>  기사  >  백엔드 개발  >  C 언어에서는 pthread_equal() 함수를 사용하여 두 스레드 ID가 동일한지 비교합니다.

C 언어에서는 pthread_equal() 함수를 사용하여 두 스레드 ID가 동일한지 비교합니다.

WBOY
WBOY앞으로
2023-09-22 16:29:021144검색

C 언어에서는 pthread_equal() 함수를 사용하여 두 스레드 ID가 동일한지 비교합니다.

pthread_equal() 함수는 두 스레드가 동일한지 확인하는 데 사용됩니다. 0 또는 0이 아닌 값을 반환합니다. 동일한 스레드에 대해서는 0이 아닌 값을 반환하고, 그렇지 않으면 0을 반환합니다. 이 함수의 구문은 다음과 같습니다.

int pthread_equal (pthread_t th1, pthread_t th2);

이제 pthread_equal()이 실제로 무엇을 하는지 살펴보겠습니다. 첫 번째 경우에는 자체 스레드를 확인하여 결과를 확인합니다.

Example

#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
}

Output

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으로 문의하시기 바랍니다. 삭제