Threads are semi-processes or low weight processes that have its own stack, and executes given piece of code. Unlike processes, the memory is shared with other threads thus can share global variables, same heap memory, and same set of file descriptors. Threads execute in parallel assuming system has several processors.

Advantages of threads over processes:

  • Less time to create a new thread as newly created threads uses the current process address space.
  • Less termination time and switching time from one thread to other (because using same address space)
  • Less communication overheads that means data produced by one thread is easily available to all other threads.

Multithread

Benefits of Multithreading:

  • Better responsiveness: One does not have to wait for one activity to complete before starting other.
  •  Multiprocessors used more efficiently.
  • Less use of system resources.
  • More adaptive and better program structure.

Thread Libraries :

Interface to multithreading support is through a subroutine library,

  • libpthread for POSIX thread
  • libthread for Solaris thread

    They contains code for :

  • creating & destroying threads
  • data communication
  • scheduling execution of threads
  • saving & restoring thread contexts

Unlike programming languages like Java, multithreading is not supported by C language standard. Implementation of POSIX thread is available in gcc compilers using POSIX standards.

Creating  threads :

pthread_create(thread,attr,routine,arg) :

It creates a new thread and makes it executable. This routine can be called any number of times from anywhere within our code. It has four arguments which are described below :

thread : unique ID for the new thread created. A integer can be passed which identifies the thread in the system.

attr : To set thread attributes. NULL is used for default values.

routine : Name of the function to be executed for the thread created.

arg : The single argument which can be passed through routine via thread. NULL when nothing to be passed.

Once a thread is created , it can create other threads.

pthread_join(thread,NULL) :

It is equivalent to wait() function for processes.  It suspend execution of the calling thread until the target threadterminates.

*sleep() : Suspend execution by real time seconds specified by argument.

Our first thread :

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

void *first(void *arg)
{
    sleep(1);
    printf(" Thread is running :) \n");
    printf("%s\n",arg);
    return NULL;
}
  
int main()
{
    pthread_t id;
    printf("Thread yet to run\n");
    pthread_create(&id, NULL, first, "I am the parameter in thread.");
    pthread_join(id, NULL);
    printf("Thread terminated .\n");
    exit(0);
}

Leave a Reply