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

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.

How it works

The API to create a thread is

  • 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.


Related Contents to follow