diff --git a/threads-sema/Makefile b/threads-sema/Makefile index 4619c72..927d969 100644 --- a/threads-sema/Makefile +++ b/threads-sema/Makefile @@ -1,9 +1,19 @@ +CC := gcc +CFLAGS := -Wall -Werror -I../include -FLAGS = -Wall -pthread -I../include +SRCS := dining_philosophers_deadlock.c dining_philosophers_deadlock_print.c dining_philosophers_no_deadlock.c dining_philosophers_no_deadlock_print.c join.c -all: - gcc $(FLAGS) -o dining_philosophers_deadlock dining_philosophers_deadlock.c - gcc $(FLAGS) -o dining_philosophers_deadlock_print dining_philosophers_deadlock_print.c - gcc $(FLAGS) -o dining_philosophers_no_deadlock dining_philosophers_no_deadlock.c - gcc $(FLAGS) -o dining_philosophers_no_deadlock_print dining_philosophers_no_deadlock_print.c +OBJS := ${SRCS:c=o} +PROGS := ${SRCS:.c=} +.PHONY: all +all: ${PROGS} + +${PROGS} : % : %.o Makefile + ${CC} $< -o $@ -pthread + +clean: + rm -f ${PROGS} ${OBJS} + +%.o: %.c Makefile + ${CC} ${CFLAGS} -c $< diff --git a/threads-sema/README.md b/threads-sema/README.md index a6804c4..6095a32 100644 --- a/threads-sema/README.md +++ b/threads-sema/README.md @@ -1,4 +1,15 @@ +# Fork/Join + +Simple example of the fork/join (i.e., waiting for a child) problem +using semaphores, found in `join.c`. + +Run `make` to build the code; run `join` to test it. Fun! + + + + + # Dining Philosophers The dining philosophers example from the text is found herein, in a few diff --git a/threads-sema/join.c b/threads-sema/join.c new file mode 100644 index 0000000..e9de1ff --- /dev/null +++ b/threads-sema/join.c @@ -0,0 +1,27 @@ +#include +#include +#include +#include + +#include "common.h" +#include "common_threads.h" + +sem_t s; + +void *child(void *arg) { + sleep(4); + printf("child\n"); + Sem_post(&s); // signal here: child is done + return NULL; +} + +int main(int argc, char *argv[]) { + Sem_init(&s, 0); + printf("parent: begin\n"); + pthread_t c; + Pthread_create(&c, NULL, child, NULL); + Sem_wait(&s); // wait here for child + printf("parent: end\n"); + return 0; +} +