We touched upon mutexes and what they are; now we are going to implement a C program that demonstrates how they work.
Create a new file called third_c_prog.c
inside the c_programs
directory.
vim third_c_prog.c
Add the following code to this file:
#include <stdio.h> #include <stdlib.h> #include <pthread.h> pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_t thread_id[4]; int counter = 0; void *thread_processor() { pthread_mutex_lock( &mutex1 ); counter++; printf(" Counter: %d\n",counter); pthread_mutex_unlock( &mutex1 ); } int main(void) { int i = 0; int error; while(i < 4) { error = pthread_create(&(thread_id[i]), NULL, &thread_processor, NULL); if (error != 0) { printf("\nthere was a problem creating thread: %s", strerror(error)); } else { printf("\n Thread number %d created.\n", i); } pthread_join( thread_id[i], NULL); i++; } }
This program is a variation on the first...