-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblem-19
More file actions
37 lines (29 loc) · 951 Bytes
/
problem-19
File metadata and controls
37 lines (29 loc) · 951 Bytes
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
#include <stdio.h>
#include <pthread.h>
// Shared variable
int counter = 0;
pthread_mutex_t mutex;
// Function to be executed by threads
void* threadFunction(void *arg) {
for (int i = 0; i < 1000000; ++i) {
pthread_mutex_lock(&mutex); // Lock the mutex before modifying the counter
++counter;
pthread_mutex_unlock(&mutex); // Unlock the mutex after modifying the counter
}
return NULL;
}
int main() {
pthread_mutex_init(&mutex, NULL); // Initialize the mutex
pthread_t thread1, thread2;
// Create threads
pthread_create(&thread1, NULL, threadFunction, NULL);
pthread_create(&thread2, NULL, threadFunction, NULL);
// Wait for the threads to finish
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
// Destroy the mutex
pthread_mutex_destroy(&mutex);
// Print the final value of the counter
printf("Final counter value: %d\n", counter);
return 0;
}