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 | /*
* Copyright 2021 Jeisson Hidalgo-Cespedes - Universidad de Costa Rica
* Creates a secondary thread that greets in the standard output
*/
#include <inttypes.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
void* run(void* data);
int create_threads(size_t thread_count);
// TODO(you): do not use global variables
pthread_mutex_t stdout_mutex;
int main(int argc, char* argv[]) {
int error = pthread_mutex_init(&stdout_mutex, /*attr*/ NULL);
if (error == 0) {
size_t thread_count = 1;
if (argc >= 2) {
thread_count = strtoull(argv[1], NULL, 10);
}
error = create_threads(thread_count);
pthread_mutex_destroy(&stdout_mutex);
} else {
fprintf(stderr, "error: could not init mutex\n");
error = 11;
}
return error;
}
int create_threads(size_t thread_count) {
pthread_t* threads = (pthread_t*) malloc(thread_count * sizeof(pthread_t));
int error = 0;
if (threads) {
for (size_t index = 0; index < thread_count; ++index) {
/*&stdout_mutex*/
error = pthread_create(&threads[index], NULL, run, (void*)index);
if (error) {
fprintf(stderr, "error: could not create thread %zu\n", index);
error = 21;
}
}
pthread_mutex_lock(&stdout_mutex);
printf("Hello from main thread\n");
pthread_mutex_unlock(&stdout_mutex);
for (size_t index = 0; index < thread_count; ++index) {
pthread_join(threads[index], NULL);
}
free(threads);
} else {
fprintf(stderr, "error: could not allocate memory for %zu threads\n"
, thread_count);
error = 22;
}
return error;
}
void* run(void* data) {
// pthread_mutex_t* stdout_mutex = (pthread_mutex_t*)data;
pthread_mutex_lock(&stdout_mutex);
printf("Hello from secondary thread %zu\n", (size_t)data);
pthread_mutex_unlock(&stdout_mutex);
return NULL;
}
#if 0
for (int index = 0; index < argc; ++index) {
printf("argv[%d] = {%s}\n", index, argv[index]);
}
#endif
|