simple join example
This commit is contained in:
@@ -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:
|
OBJS := ${SRCS:c=o}
|
||||||
gcc $(FLAGS) -o dining_philosophers_deadlock dining_philosophers_deadlock.c
|
PROGS := ${SRCS:.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
|
|
||||||
|
|
||||||
|
.PHONY: all
|
||||||
|
all: ${PROGS}
|
||||||
|
|
||||||
|
${PROGS} : % : %.o Makefile
|
||||||
|
${CC} $< -o $@ -pthread
|
||||||
|
|
||||||
|
clean:
|
||||||
|
rm -f ${PROGS} ${OBJS}
|
||||||
|
|
||||||
|
%.o: %.c Makefile
|
||||||
|
${CC} ${CFLAGS} -c $<
|
||||||
|
|||||||
@@ -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
|
# Dining Philosophers
|
||||||
|
|
||||||
The dining philosophers example from the text is found herein, in a few
|
The dining philosophers example from the text is found herein, in a few
|
||||||
|
|||||||
27
threads-sema/join.c
Normal file
27
threads-sema/join.c
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
#include <stdio.h>
|
||||||
|
#include <stdlib.h>
|
||||||
|
#include <pthread.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
|
#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;
|
||||||
|
}
|
||||||
|
|
||||||
Reference in New Issue
Block a user