Thread Synchronization with Semaphores - BunksAllowed

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

Community

demo-image

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#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);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Happy Exploring!

Comment Using!!

No comments:

Post a Comment

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