From 9b46e5890d5f2e202c5927ced705eef69149800c Mon Sep 17 00:00:00 2001 From: Dimitri Sokolyuk Date: Sat, 3 Oct 2009 20:08:59 +0000 Subject: add pthreads --- Makefile | 2 +- weasel.c | 46 ++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/Makefile b/Makefile index 3ed81cd..210a89e 100644 --- a/Makefile +++ b/Makefile @@ -3,6 +3,6 @@ PROG= weasel NOMAN= DEBUG+= -Wall -ggdb -LDADD+= -lcurses +LDADD+= -lcurses -lpthread . include diff --git a/weasel.c b/weasel.c index 5ba3ffe..fe00e22 100644 --- a/weasel.c +++ b/weasel.c @@ -18,12 +18,22 @@ #include #include #include +#include #include #include #include #include #include +#define NUM_THREADS 10 +pthread_t threads[NUM_THREADS]; +pthread_mutex_t mutexsum; + +struct intargs { + int mutationrate; + int population; +}; + #if 0 const char defaim[] = "METHINKS IT IS LIKE A WEASEL"; const char alphabet[] = " ABCDEEFGHIJKLMNOPQRSTUVWXYZ"; @@ -39,6 +49,7 @@ struct creature { char *genom; int length; float fitness; + int locked; TAILQ_ENTRY(creature) link; } *cp; @@ -78,6 +89,7 @@ initpopulation(int length, int number) cp->genom[i] = '\0'; cp->length = length; cp->fitness = calculatefitness(cp->genom, cp->length); + cp->locked = 0; TAILQ_INSERT_HEAD(&generation, cp, link); } } @@ -106,8 +118,14 @@ pickrandom(int population) int n = arc4random() % population; cp = TAILQ_FIRST(&generation); - while (n-- && cp) + while (n-- > 0 && cp) cp = TAILQ_NEXT(cp, link); + if (cp->locked) + cp = pickrandom(population); + + pthread_mutex_lock(&mutexsum); + cp->locked = 1; + pthread_mutex_unlock(&mutexsum); return cp; } @@ -141,6 +159,10 @@ intercourse(int population, int mutationsrate) } c[2]->genom[i] = '\0'; c[2]->fitness = calculatefitness(c[2]->genom, c[2]->length); + + c[0]->locked = 0; + c[1]->locked = 0; + c[2]->locked = 0; } int @@ -162,13 +184,25 @@ success() return best->fitness == 1.0; } +void * +ptintercourse(void *args) +{ + struct intargs *ia = args; + + intercourse(ia->population, ia->mutationrate); + + pthread_exit(NULL); +} + + int main(int argc, char **argv) { + struct intargs args; extern int LINES; int population = 1000; int mutationrate = 100; /* 1/n */ - int i, c; + int i, c, t; while ((c = getopt(argc, argv, "m:p:")) != -1) switch (c) { @@ -191,16 +225,20 @@ main(int argc, char **argv) setterm("vt220"); initpopulation(strlen(aim), population); + args.population = population; + args.mutationrate = mutationrate; + for (i = 0;; i++) { move(0, 0); - intercourse(population, mutationrate); + for (t = 0; t < NUM_THREADS; t++) + pthread_create(&threads[t], NULL, ptintercourse, (void *)&args); printpopulation(LINES - 8); if (success()) break; refresh(); } - printw("\nhalted after %d generations\n", i / population); + printw("\nhalted after %d generations\n", NUM_THREADS * i / population); refresh(); endwin(); -- cgit v1.2.3