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.

Online courses related to this article


Course description

Learn to develop embedded systems, interfacing electronic peripherals through real time projects and get required practical skills for software jobs



Course description

Learn to develop software solutions for linux environment, implement requirements through real time projects and get required practical skills for software jobs

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
    pthread_mutex_lock(&mutex);
    result += aoffset;
    //End critical section
    pthread_mutex_unlock(&mutex);
  }
  pthread_exit(NULL);
}

void *SubtractFunc(void *s) {
  int soffset = *(int *) s;
  for(int j = 0; j < LOOPS; j++) {
    //Start critical section
    pthread_mutex_lock(&mutex);
    result += soffset;
    //End critical section
    pthread_mutex_unlock(&mutex);
  }
  pthread_exit(NULL);
}

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


Articles


Linux Software

More Articles Categories

Technical articles

Prepare for software jobs


Test your skills