# =============================================================================
# Makefile for CMU 15-213 Lecture 22 (synchronization -- basic)
# =============================================================================
#
#   make run      the race and its three fixes; the cost of each; the assembly
#   make clean
#
# psem.{c,h} is this lecture's portable semaphore: macOS has no working
# sem_init(), so it uses named semaphores there. Lecture 23 links it too.
# 03 is a Python driver that inspects compiler output (as Lecture 15 did).
# -----------------------------------------------------------------------------

CC     ?= cc
CFLAGS := -std=c11 -O2 -Wall -Wextra
LDLIBS := -lpthread

.PHONY: all run clean
all: build/01_badcnt_O0 build/01_badcnt_O2 build/02_sync_cost

build:
	mkdir -p build

build/psem.o: psem.c psem.h | build
	$(CC) $(CFLAGS) -c -o $@ psem.c

# psem.o is built at -O2 either way; only the demo's own loops change.
# -O0: the increment loop is real, so the race appears in full.
# -O2: the compiler collapses the loop, which HIDES the race -- see the notes.
build/01_badcnt_O0: 01_badcnt.c psem.h build/psem.o | build
	$(CC) -std=c11 -O0 -Wall -Wextra -DOPTLEVEL='"-O0"' \
	      -o $@ 01_badcnt.c build/psem.o $(LDLIBS)

build/01_badcnt_O2: 01_badcnt.c psem.h build/psem.o | build
	$(CC) -std=c11 -O2 -Wall -Wextra -DOPTLEVEL='"-O2"' \
	      -o $@ 01_badcnt.c build/psem.o $(LDLIBS)

build/02_sync_cost: 02_sync_cost.c psem.h build/psem.o | build
	$(CC) $(CFLAGS) -o $@ 02_sync_cost.c build/psem.o $(LDLIBS)

run: all
	@echo "######## the race at -O0: the loop is real ########"
	@./build/01_badcnt_O0
	@echo
	@echo "######## the same source at -O2: the optimizer HIDES it ########"
	@./build/01_badcnt_O2
	@echo; ./build/02_sync_cost
	@echo; python3 03_why_it_races.py

clean:
	rm -rf build __pycache__
