当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


C语言 pthread_equal()用法及代码示例


先决条件:多线程,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 <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <pthread.h> 
  
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 <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/types.h> 
#include <pthread.h> 
  
// 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



注:本文由纯净天空筛选整理自 pthread_equal() in C with example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。