17 Basic Demonstration of Pthread Library in C

Program:

   
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

// Pointer Function
void *routine(void *i)
{
    printf("\n Test from threads: %s",(char *) i);
    sleep(3);
    printf("\n Thread Ending");
}

int main()
{
    // pthread_t is the data type used to uniquely identify a thread
    // it is of 4 byte
    pthread_t t1,t2;    
    
    /*
    int pthread_create(pthread_t *thread, pthread_attr_t *attr,
                   void *(*start_routine) (void *arg), void *arg);
    
    If successful, pthread_create() returns 0.

    If unsuccessful, pthread_create() returns -1 
    */

    char arg[] = "Thread 1";

    // Argument to Pthread: All arguments must be passed by reference and cast to (void *).
    pthread_create(&t1, NULL,&routine, (void *) &arg );
    
    char arg2[] = "Thread 2";
    pthread_create(&t2, NULL,&routine,(void *) &arg2 );

    // The pthread_join() function waits for a thread to terminate, detaches the thread, then 
    // returns the threads exit status.
    // int pthread_join(pthread_t thread, void **retval);
    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
   
    return 0;
}
    

Output:

pthread_create


Previous
Next Post »