Thread Synchronization with Mutex using C Programming - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Thread Synchronization with Mutex using C Programming

Share This

In the previous tutorial, we used a semaphore for thread synchronization. Here, we will discuss another technique of synchronization.

In this technique, an object is locked by a thread programmatically so that other threads do not get access to the object until it is being released. The following program illustrates the technique.

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <semaphore.h> #define SIZE 1024 void *thread_function(void *arg); pthread_mutex_t mutex_val; char str[SIZE]; int time_to_exit = 0; int main() { int res; pthread_t my_thread_a; void *thread_result; res = pthread_mutex_init(&mutex_val, NULL); if (res != 0) { perror("Mutex initialization failed"); exit(EXIT_FAILURE); } res = pthread_create(&my_thread_a, NULL, thread_function, NULL); if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } pthread_mutex_lock(&mutex_val); printf("Input some text. Enter end to finish\n"); while (!time_to_exit) { fgets(str, SIZE, stdin); pthread_mutex_unlock(&mutex_val); while (1) { pthread_mutex_lock(&mutex_val); if (str[0] != '\0') { pthread_mutex_unlock(&mutex_val); sleep(1); } else { break; } } } pthread_mutex_unlock(&mutex_val); printf("\nWaiting for thread to finish...\n"); res = pthread_join(my_thread_a, &thread_result); if (res != 0) { perror("Thread join failed"); exit(EXIT_FAILURE); } printf("Thread joined\n"); pthread_mutex_destroy(&mutex_val); exit(EXIT_SUCCESS); } void *thread_function(void *arg) { sleep(1); pthread_mutex_lock(&mutex_val); while (strncmp("end", str, 3) != 0) { printf("You input %d characters\n", strlen(str) -1); str[0] = '\0'; pthread_mutex_unlock(&mutex_val); sleep(1); pthread_mutex_lock(&mutex_val); while (str[0] == '\0' ) { pthread_mutex_unlock(&mutex_val); sleep(1); pthread_mutex_lock(&mutex_val); } } time_to_exit = 1; str[0] = '\0'; pthread_mutex_unlock(&mutex_val); pthread_exit(0); }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.