From: Julian Seward Date: Thu, 16 May 2002 23:30:25 +0000 (+0000) Subject: Add a test for semaphore facilities: the Dining Philosophers, no less. X-Git-Tag: svn/VALGRIND_1_0_3~184 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=4bc87a6ab380b2e928d30a630e91d217a37f38f8;p=thirdparty%2Fvalgrind.git Add a test for semaphore facilities: the Dining Philosophers, no less. git-svn-id: svn://svn.valgrind.org/valgrind/trunk@282 --- diff --git a/tests/Makefile.am b/tests/Makefile.am index 964d390874..9db71ca411 100644 --- a/tests/Makefile.am +++ b/tests/Makefile.am @@ -28,4 +28,4 @@ EXTRA_DIST = \ bt_everything.c bt_literal.c \ pth_threadpool.c pth_specific.c pth_mutexspeed.c malloc3.c \ pth_once.c weirdioctl.c pth_signal1.c pth_signal2.c \ - discard.c + discard.c pth_semaphore1.c diff --git a/tests/pth_semaphore1.c b/tests/pth_semaphore1.c new file mode 100644 index 0000000000..17181561e5 --- /dev/null +++ b/tests/pth_semaphore1.c @@ -0,0 +1,70 @@ + +/* Dining philosophers, using semaphores. From the Ben-Ari book. */ + +#include +#include +#include +#include + +#define N_PHILOSOPHERS 5 + +sem_t room; +sem_t forc[N_PHILOSOPHERS]; +pthread_t tid[N_PHILOSOPHERS]; + +void eat ( int i ) +{ + printf("%d -> begin eat\n", i); + i += 17; + i *= 10000; + while (i > 0) i--; + printf("%d -> end eat\n", i); +} + +void think ( int i ) +{ + printf("%d -> begin think\n", i); + i += 23; + i *= 9000; + while (i > 0) i--; + printf("%d -> end think\n", i); +} + +void* philosopher ( void* vi ) +{ + int i = (int)vi; + int res; + int rounds; + for (rounds = 0; rounds < 10; rounds++) { + think(i); + res = sem_wait(&room); assert(res == 0); + res = sem_wait(&forc[i]); assert(res == 0); + res = sem_wait(&forc[(i+1) % N_PHILOSOPHERS]); assert(res == 0); + eat(i); + res = sem_post(&forc[i]); assert(res == 0); + res = sem_post(&forc[(i+1) % N_PHILOSOPHERS]); assert(res == 0); + res = sem_post(&room); assert(res == 0); + } + return NULL; +} + +int main ( void ) +{ + int i, res; + + res = sem_init(&room, 0, 4); assert(res == 0); + for (i = 0; i < N_PHILOSOPHERS; i++) { + res = sem_init ( &forc[i], 0, 1 ); + assert(res == 0); + } + + for (i = 0; i < N_PHILOSOPHERS; i++) { + res = pthread_create ( &tid[i], NULL, philosopher, (void*)i ); + assert(res == 0); + } + for (i = 0; i < N_PHILOSOPHERS; i++) { + res = pthread_join ( tid[i], NULL ); + assert(res == 0); + } + return 0; +}