pthread_equal() 함수는 두 스레드가 동일한지 여부를 확인하는 데 사용됩니다. 0 또는 0이 아닌 값을 반환합니다. 동일한 스레드의 경우 0이 아닌 값을 반환하고 그렇지 않으면 0을 반환합니다. 이 함수의 구문은 다음과 같습니다. -
int pthread_equal (pthread_t th1, pthread_t th2);
이제 pthread_equal()이 작동하는 것을 보겠습니다. 첫 번째 경우에는 self-thread를 확인하여 결과를 확인합니다.
예시
#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\n");
} else {
printf("Threads are not equal\n");
}
}
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\n");
} else {
printf("Threads are not equal\n");
}
}
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