From 98a99ac340518d66c81df28f514232d930610500 Mon Sep 17 00:00:00 2001 From: Camden Dixie O'Brien Date: Fri, 25 Nov 2022 00:13:19 +0000 Subject: [PATCH] Run 8 solving threads in parallel --- Makefile | 6 +++++- main.c | 42 +++++++++++++++++++++++++++++++++++------- 2 files changed, 40 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index a7ba07d..47b33ea 100644 --- a/Makefile +++ b/Makefile @@ -22,12 +22,16 @@ CFLAGS += -D_XOPEN_SOURCE=700 CFLAGS += -march=native CFLAGS += -static +LDFLAGS += -lpthread + # For profiling # CFLAGS += -pg SRC = main.c sud.c solve.c OBJ = $(SRC:.c=.o) +default: sudoku eval + sudoku: $(OBJ) $(CC) $(CFLAGS) $(LDFLAGS) $(OBJ) -o $@ @@ -55,4 +59,4 @@ run: sudoku eval puzzles solns results time ./sudoku ./eval -.PHONY: clean run +.PHONY: default clean run diff --git a/main.c b/main.c index f5a047f..78e0884 100644 --- a/main.c +++ b/main.c @@ -21,6 +21,7 @@ #include "sud.h" #include +#include #include #include #include @@ -31,6 +32,29 @@ #define OFNAME "results" #define FSIZE (NPUZZ * NCELLS) +#define NTHREADS 8U +#define PUZZPT (NPUZZ / NTHREADS) +#define CELLPT (PUZZPT * NCELLS) + +static char *ibuf; +static char *obuf; + +void *threadproc(void *arg) +{ + unsigned start = CELLPT * (uintptr_t)arg; + const char *libuf = ibuf + start; + char *lobuf = obuf + start; + + struct sudoku sud; + for (unsigned o = 0; o < CELLPT; o += NCELLS) { + load(&sud, libuf + o); + solve(&sud); + save(&sud, lobuf + o); + } + + return NULL; +} + int main(void) { int fd; @@ -40,7 +64,7 @@ int main(void) fputs("Failed to open puzzles file\n", stderr); return EXIT_FAILURE; } - char *ibuf = mmap(NULL, FSIZE, PROT_READ, MAP_PRIVATE, fd, 0); + ibuf = mmap(NULL, FSIZE, PROT_READ, MAP_PRIVATE, fd, 0); if (ibuf == MAP_FAILED) { fputs("Failed to mmap() puzzles file\n", stderr); return EXIT_FAILURE; @@ -52,18 +76,22 @@ int main(void) fputs("Failed to open results file\n", stderr); return EXIT_FAILURE; } - char *obuf = mmap(NULL, FSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + obuf = mmap(NULL, FSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (obuf == MAP_FAILED) { fputs("Failed to mmap() results file\n", stderr); return EXIT_FAILURE; } close(fd); - struct sudoku sud; - for (unsigned o = 0; o < FSIZE; o += NCELLS) { - load(&sud, ibuf + o); - solve(&sud); - save(&sud, obuf + o); + pthread_t pool[NTHREADS]; + uintptr_t i; + for (i = 0; i < NTHREADS; ++i) { + if (pthread_create(&pool[i], NULL, threadproc, (void *)i) != 0) + fprintf(stderr, "Failed to create thread #%lu\n", i); + } + for (i = 0; i < NTHREADS; ++i) { + if (pthread_join(pool[i], NULL) != 0) + fprintf(stderr, "Failed to join thread #%lu\n", i); } munmap(ibuf, FSIZE);