pthreads practical applications illustration in linux

In this article we will look at pthreads creation, management and applications in linux operating system using practical examples, code snippets. Subscribe to earn a certificate from our online courses listed . Your low cost subscription will enable complete access to all , , to clear all online course requirements.

Article contents

Multithreading example program

pthread creation and join.
Multithreading program.

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

#define LOOPS 1000
int result = 0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 

void *AddFunc(void *a) {
  int aoffset = *(int *) a;
  for(int i = 0; i < LOOPS; i++) {
    //Start critical section
    result += aoffset;
    //End critical section

void *SubtractFunc(void *s) {
  int soffset = *(int *) s;
  for(int j = 0; j < LOOPS; j++) {
    //Start critical section
    result += soffset;
    //End critical section

int main(void) {
  pthread_t thread_id1;
  pthread_t thread_id2;

  int offset1 = 1, offset2 = -1;
  pthread_create(&thread_id1, NULL, AddFunc, &offset1);
  pthread_create(&thread_id2, NULL, SubtractFunc, &offset2);

  //Wait for threads to finish
  pthread_join(thread_id1, NULL);
  pthread_join(thread_id2, NULL);

  printf("The result is:%d\n", result);

  return 0;
Let's compile the Listing1.c program as shown in the following program output.
pi@raspberrypi:~/try $ gcc prog.c -lpthread
pi@raspberrypi:~/try $ ./a.out
The result is:0
pi@raspberrypi:~/try $

Want to contribute or ask a new article? Write and upload your article information .


Linux Software

More Articles Categories

Technical articles

Prepare for software jobs

Test your skills