Thread Synchronization with Semaphores - BunksAllowed

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

Random Posts

Thread Synchronization with Semaphores

Share This

Multi-Threaded programming with a critical section is a quite difficult problem. In the simplest form, these problems require semaphores to synchronize them. In this context, the following program illustrates how semaphore is used for multi-threading problems with critical sections.

#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <semaphore.h> #define SIZE 1024 void *my_thread_function(void *arg); sem_t binary_semaphore_var; char str[SIZE]; int main() { int res; pthread_t my_thread_a; void *thread_result; res = sem_init(&binary_semaphore_var, 0, 0); if (res != 0) { perror("Semaphore initialization failed"); exit(EXIT_FAILURE); } res = pthread_create(&my_thread_a, NULL, my_thread_function, NULL); if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } printf("Input some text or enter end to finish\n"); while (strncmp("end", str, 3) != 0) { fgets(str, SIZE, stdin); sem_post(&binary_semaphore_var); } 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"); sem_destroy(&binary_semaphore_var); exit(EXIT_SUCCESS); } void *my_thread_function(void *arg) { sem_wait(&binary_semaphore_var); while (strncmp("end", str, 3) != 0) { printf("You input %d characters\n", strlen(str) -1); sem_wait(&binary_semaphore_var); } pthread_exit(NULL); }

Happy Exploring!

No comments:

Post a Comment