-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfizzbuzz027.c
67 lines (61 loc) · 1.54 KB
/
fizzbuzz027.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
#define _POSIX_C_SOURCE 199309L
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
static void die(char *message) {
fprintf(stderr, "%s\n", message);
exit(EXIT_FAILURE);
}
struct dstring {
char *str;
bool allocated;
};
static void *thread_routine(void *arg) {
const int i = *(int*)arg;
struct dstring *result = malloc(sizeof *result);
if (result == NULL) {
die("malloc failed");
}
if (i % 15 == 0) {
*result = (struct dstring){ .str = "FizzBuzz", .allocated = false };
}
else if (i % 3 == 0) {
*result = (struct dstring){ .str = "Fizz", .allocated = false };
}
else if (i % 5 == 0) {
*result = (struct dstring){ .str = "Buzz", .allocated = false };
}
else {
char *str = malloc(4);
if (str == NULL) {
die("malloc failed");
}
sprintf(str, "%d", i);
*result = (struct dstring){ .str = str, .allocated = true };
}
return result;
}
static struct dstring *line(int i) {
pthread_t thr;
int result = pthread_create(&thr, NULL, thread_routine, &i);
if (result != 0) {
die("Error in pthread_create");
}
void *retval;
result = pthread_join(thr, &retval);
if (result != 0) {
die("Error in pthread_join");
}
return retval;
}
int main(void) {
for (int i = 1; i <= 100; i ++) {
struct dstring *dline = line(i);
puts(dline->str);
if (dline->allocated) {
free(dline->str);
}
free(dline);
}
}