Open In App

pthread_equal() in C with example

Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite : Multithreading, pthread_self() in C with Example

pthread_equal() = This compares two thread which is equal or not. This function compares two thread identifiers. It return ‘0’ and non zero value. If it is equal then return non zero value else return 0.

Syntax:- int pthread_equal (pthread_t t1, pthread_t t2);

 

First Method :- Compare with self thread




// 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);
}


Output:

equal

 

Second Method :- Compare with other thread




// 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);
}


Output:

not equal


Last Updated : 14 Oct, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads