-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreads.c
More file actions
90 lines (69 loc) · 1.88 KB
/
threads.c
File metadata and controls
90 lines (69 loc) · 1.88 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
/*
* Add NetID and names of all project partners
Pavan Kumar Kokkiligadda : pkk46
Nicholas Chen : nhc29
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
pthread_t t1, t2, t3, t4;
pthread_mutex_t mutex;
int x = 0;
int loop = 10000;
/* Counter Incrementer function:
* This is the function that each thread will run which
* increments the shared counter x by LOOP times.
*
* Your job is to implement the incrementing of x
* such that update to the counter is sychronized across threads.
*
*/
void *add_counter(void *arg)
{
int i;
/* Add thread synchronizaiton logic in this function */
// Lock the mutex before updating the shared variable
pthread_mutex_lock(&mutex);
for (i = 0; i < loop; i++)
{
x = x + 1;
}
// Unlock the mutex after updating the shared variable
pthread_mutex_unlock(&mutex);
return NULL;
}
/* Main function:
* This is the main function that will run.
*
* Your job is to create four threads and have them
* run the add_counter function().
*/
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Bad Usage: Must pass in a integer\n");
exit(1);
}
loop = atoi(argv[1]);
printf("Going to run four threads to increment x up to %d\n", 4 * loop);
/* Implement Code Here */
// Initialize mutex
pthread_mutex_init(&mutex, NULL);
/* Create threads */
pthread_create(&t1, NULL, add_counter, NULL);
pthread_create(&t2, NULL, add_counter, NULL);
pthread_create(&t3, NULL, add_counter, NULL);
pthread_create(&t4, NULL, add_counter, NULL);
/* Join threads */
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
pthread_join(t4, NULL);
// Destroy mutex
pthread_mutex_destroy(&mutex);
/* Make sure to join the threads */
printf("The final value of x is %d\n", x);
return 0;
}