C 语言中的 pthread_equal() 函数
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
"); } 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 }
输出
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
"); } 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); }
输出
Threads are not equal
广告