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.
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#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);
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.