In this article we will look at pthreads creation, management and applications in linux operating system using practical examples, code snippets. Subscribe here to earn a certificate from our online courses listed here. Your low cost subscription will enable complete access to all technical articles, online tests, projects to clear all online course requirements.
#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 $
Share | Tweet |
---|