This blog pots discuss about basic concept of multithreading in c under Linux operating system. what is thread? A thread is lightweight process. it is a sequence of control within a process. Linux provides posix based api for creating and manging threads. posix means portable operating system interface.

sample code for multithreading in c

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

void *foo(void *vargp)
{
	sleep(5);
	printf("Hello from Thread \n");
}

int main() {
	pthread_t thread_id;
	printf("Creating a Thread....\n");
	pthread_create(&thread_id, NULL, foo, NULL);
	pthread_join(thread_id, NULL);
	return 0;
}

How to compile pthread program

  • Save the above code as sample.c.
  • Compile using command “gcc sample.c -o sample -lpthread”
  • We need to link our thread program with pthread library using -lpthread otherwise it will not compile.
  • Run the sample.
bosch@bosch-Inspiron-N5050:~$ ./sample 
Creating a Thread....
Hello from Thread 

How it works

The API to create a thread is

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);
  • The first argument is address of thread id.
  • The second argument is pthread attribute. In our sample code we have passed NULL. We Pass NULL attribute if we do not want to change default thread attributes.
  • The third argument is a function which will be called in thread. The third argument must be a function which takes a void pointer and returns a void pointer.
  • The last argument is a parameter to pass in function.
  • pthread_join will suspend execution of the thread that has called it unless the target thread terminates.

Why thread is called lightweight process?

A thread is a sequence of control in a process. When we create a new thread inside a process, thread gets its own stack segments but shares global data/variables, file descriptor,signal handler of the process that has created thread.

Ref:

https://en.wikipedia.org/wiki/POSIX

http://stackoverflow.com/questions/20824229/when-to-use-pthread-exit-and-when-to-use-pthread-join-in-linux



Related Contents to follow