POSIX Thread Programming

What is Thread:

 A thread is defined as an independent stream of instructions that can be scheduled to run as such by the operating system. For example, Suppose in your main program, you want to execute some process independently such as timer, then in this case you can create thread. 

Why Pthread:

: Light weight

: Easy to exchange data and efficiently

When we create threads in applications, we must handle and take care of memory leakage. Free resources which is occupied by thread such as files.

To use pthreads, you can use Pthreads API which is defined in the ANSI/IEEE POSIX 1003.1 – 1995 standard. Using this API, you can create synchronous threads, you can implement mutex.

Pthread API identifiers begins with pthread_ like pthread_mutexattr_ , pthread_attr_ etc.

Compiling Pthread Program:

To compile, You need to enable pthread library and add -lpthread in end of compilation code.

This Example create 5 threads and prints “Hello World” message and then it terminates.

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5

void *PrintHello(void *threadid)
{
   printf("Hello World! It's me, thread #%ld!\n", (long)threadid);
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc;
   long t;
   for(t=0; t<NUM_THREADS; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }
   }

   /* Last thing that main() should do */
   pthread_exit(NULL);
}

pthread_create: Used to create thread.

pthread_exit: Used to terminate thread.

You should use pthread_join, this function blocks the calling thread until the specified threadid thread terminates.

 

Thanks

Sharad Sinha

 

 

Leave a Reply