-
Notifications
You must be signed in to change notification settings - Fork 0
/
multiRobot.c
80 lines (66 loc) · 1.74 KB
/
multiRobot.c
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
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "consoleUtils.h"
#define total_num_steps 1000
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int _cur_leg = 0;
int _cur_step = 0;
int _total_legs_num = 0;
void *take_step(void *args)
{
size_t this_leg_num = (size_t) args;
int total_leg_num = _total_legs_num;
while (1)
{
pthread_mutex_lock(&mutex);
if (_cur_step == total_num_steps)
{
pthread_mutex_unlock(&mutex);
return 0;
}
else if (_cur_leg == this_leg_num)
{
_cur_leg++;
_cur_step++;
printf("Step %d, leg %lu\n", _cur_step, this_leg_num + 1);
_cur_leg = _cur_leg % total_leg_num;
}
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, char *argv[])
{
int legs_num = readNumber(argc, argv);
if (legs_num <= 0)
{
printf("Expected non-negative value, got %d", legs_num);
exit(EXIT_FAILURE);
}
// Uses global variable to do not send same information to each thread
_total_legs_num = legs_num;
pthread_t *legs = (pthread_t *) calloc((size_t) legs_num, sizeof(pthread_t));
if (!legs)
{
perror("calloc() fail");
exit(EXIT_FAILURE);
}
for (int i = 0; i < legs_num; i++)
{
if (pthread_create(&legs[i], NULL, take_step, (void *) (size_t) i) != 0)
{
fprintf(stderr, "pthread_create() fail\n");
exit(EXIT_FAILURE);
}
}
for (int i = 0; i < legs_num; i++)
{
if (pthread_join(legs[i], (void **) NULL) != 0)
{
fprintf(stderr, "pthread_join() fail\n");
exit(EXIT_FAILURE);
}
}
free(legs);
return 0;
}