From 8bcb711e085f01720c94f341adda636d9937b0b2 Mon Sep 17 00:00:00 2001 From: Remzi Arpaci-Dusseau Date: Wed, 8 May 2019 13:25:45 -0500 Subject: [PATCH] First atomicity bug example from chapter --- threads-bugs/Makefile | 25 +++++++++++++++++ threads-bugs/atomicity.c | 60 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 threads-bugs/Makefile create mode 100644 threads-bugs/atomicity.c diff --git a/threads-bugs/Makefile b/threads-bugs/Makefile new file mode 100644 index 0000000..fff9c59 --- /dev/null +++ b/threads-bugs/Makefile @@ -0,0 +1,25 @@ +CC := gcc +CFLAGS := -Wall -Werror -I../include -pthread + +OS := $(shell uname -s) +LIBS := +ifeq ($(OS),Linux) + LIBS += -pthread +endif + +SRCS := atomicity.c + +OBJS := ${SRCS:c=o} +PROGS := ${SRCS:.c=} + +.PHONY: all +all: ${PROGS} + +${PROGS} : % : %.o Makefile + ${CC} $< -o $@ ${LIBS} + +clean: + rm -f ${PROGS} ${OBJS} + +%.o: %.c Makefile + ${CC} ${CFLAGS} -c $< diff --git a/threads-bugs/atomicity.c b/threads-bugs/atomicity.c new file mode 100644 index 0000000..0f98155 --- /dev/null +++ b/threads-bugs/atomicity.c @@ -0,0 +1,60 @@ +#include +#include +#include +#include + +#include "common.h" +#include "common_threads.h" + +typedef struct { + int pid; +} proc_t; + +typedef struct { + proc_t *proc_info; +} thread_info_t; + +proc_t p; +thread_info_t th; +thread_info_t *thd; + +void *thread1(void *arg) { + printf("t1: before check\n"); + if (thd->proc_info) { + printf("t1: after check\n"); + sleep(2); + printf("t1: use!\n"); + printf("%d\n", thd->proc_info->pid); + } + return NULL; +} + +void *thread2(void *arg) { + printf(" t2: begin\n"); + sleep(1); // change to 5 to make the code "work"... + printf(" t2: set to NULL\n"); + thd->proc_info = NULL; + return NULL; +} + +int main(int argc, char *argv[]) { + if (argc != 1) { + fprintf(stderr, "usage: main\n"); + exit(1); + } + thread_info_t t; + p.pid = 100; + t.proc_info = &p; + thd = &t; + + pthread_t p1, p2; + printf("main: begin\n"); + Pthread_create(&p1, NULL, thread1, NULL); + Pthread_create(&p2, NULL, thread2, NULL); + // join waits for the threads to finish + Pthread_join(p1, NULL); + Pthread_join(p2, NULL); + printf("main: end\n"); + return 0; +} +