先决条件:C中的多线程,pthread_self()(带示例)
pthread_equal()=比较两个线程是否相等。此函数比较两个线程标识符。返回“ 0”和非零值。如果相等,则返回非零值,否则返回0。
语法:-int pthread_equal(pthread_t t1,pthread_t t2);
第一种方法:-与自线程比较
// C program to demonstrate working of pthread_equal()
#include
#include
#include
#include
#include
pthread_t tmp_thread;
void* func_one(void* ptr)
{
// in this field we can compare two thread
// pthread_self gives a current thread id
if (pthread_equal(tmp_thread, pthread_self())) {
printf("equal\n");
} else {
printf("not equal\n");
}
}
// driver code
int main()
{
// thread one
pthread_t thread_one;
// assign the id of thread one in temporary
// thread which is global declared r
tmp_thread = thread_one;
// create a thread
pthread_create(&thread_one, NULL, func_one, NULL);
// wait for thread
pthread_join(thread_one, NULL);
}
输出:
equal
第二种方法:-与其他线程比较
// C program to demonstrate working of pthread_equal()
#include
#include
#include
#include
#include
// global declared pthread_t variable
pthread_t tmp_thread;
void* func_one(void* ptr)
{
tmp_thread = pthread_self(); // assign the id of thread one in
// temporary thread which is global declared
}
void* func_two(void* ptr)
{
pthread_t thread_two = pthread_self();
// compare two thread
if (pthread_equal(tmp_thread, thread_two)) {
printf("equal\n");
} else {
printf("not equal\n");
}
}
int main()
{
pthread_t thread_one, thread_two;
// creating thread one
pthread_create(&thread_one, NULL, func_one, NULL);
// creating thread two
pthread_create(&thread_two, NULL, func_two, NULL);
// wait for thread one
pthread_join(thread_one, NULL);
// wait for thread two
pthread_join(thread_two, NULL);
}
输出:
not equal
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。