當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。