Skip to content

Commit 06c7edf

Browse files
author
Margo
committed
Add exercise code for Dobby
1 parent 9805940 commit 06c7edf

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed

synch1x/GNUmakefile

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
PROGRAMS = dobby dobby-soln
2+
all: $(PROGRAMS)
3+
4+
O ?= 2
5+
include ../common/rules.mk
6+
7+
%.o: %.c $(BUILDSTAMP)
8+
$(CC) $(CPPFLAGS) $(CFLAGS) $(DEPCFLAGS) $(O) -o $@ -c $<
9+
10+
$(PROGRAMS): %: %.o
11+
$(CC) $(CFLAGS) -pthread $(O) -o $@ $^
12+
13+
clean:
14+
rm -f *.o *.core $(PROGRAMS)
15+
rm -rf $(DEPSDIR) *.dSYM
16+
17+
.PHONY: all clean

synch1x/dobby.c

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// Solves the dobby-the-elf and the house elf problem
2+
3+
#include <errno.h>
4+
#include <pthread.h>
5+
#include <stdio.h>
6+
#include <stdlib.h>
7+
#include <string.h>
8+
#include <unistd.h>
9+
10+
#define NELVES 25
11+
#define RANDOM_INT(lo, hi) ((int)(lo + ((double)random() / RAND_MAX) * (hi - lo + 1)))
12+
13+
14+
// The argument is simply the elf's ID number
15+
void *
16+
elf_thread(void *arg)
17+
{
18+
long long id;
19+
20+
id = (long long)arg;
21+
22+
// Prepare sumptious feast
23+
usleep(RANDOM_INT(1,1000));
24+
printf("Elf %lld prepared sumptious feast!\n", id);
25+
26+
// Clean up after messy Hogwarts students
27+
usleep(RANDOM_INT(1,1000));
28+
printf("Elf %lld cleaned up after messy students!\n", id);
29+
30+
// Say, "Harry Potter is the greatest Wizard Ever."
31+
usleep(RANDOM_INT(1,1000));
32+
printf("Elf %lld: Harry Potter is the greatest Wizard Ever!\n", id);
33+
34+
return (NULL);
35+
}
36+
37+
int
38+
main(void)
39+
{
40+
pthread_t *thread_ids;
41+
42+
// Create the elf threads -- malloc space to capture their IDs because
43+
// we'll check that they all exited at the end.
44+
thread_ids = malloc(sizeof(pthread_t) * NELVES);
45+
if (thread_ids == NULL) {
46+
fprintf(stderr, "Dobby: Malloc of elf thread ids failed %s\n",
47+
strerror(errno));
48+
exit (1);
49+
}
50+
51+
for (long long i = 0; i < NELVES; i++) {
52+
if (pthread_create(thread_ids + i, NULL, &elf_thread, (void *)i) != 0) {
53+
fprintf(stderr, "Dobby: pthread_create %lld failed %s\n",
54+
i, strerror(errno));
55+
exit(1);
56+
}
57+
}
58+
59+
// TODO: Figure out how to wait on elves and when to print out Dobby's
60+
// message. (You'll have to figure out how to get the thing to place here
61+
// for the elf's ID number, then you can uncomment this.)
62+
// printf("Thanks for your work, Elf %d!\n", IDNUM);
63+
64+
free(thread_ids);
65+
66+
printf("Dobby is done\n");
67+
}
68+

0 commit comments

Comments
 (0)