From 310ac02ad74d091c0ce355eae1549b7b9c86adcf Mon Sep 17 00:00:00 2001 From: Raphael Hiesgen Date: Fri, 21 Feb 2014 14:43:55 +0100 Subject: [PATCH] Adds test for pthread. The test uses pthread to calculate the factorial of 12, with one thread for each multiplication. pthread_mutex is used for synchronization. --- tests/test_pthread_cooperation/Makefile | 14 +++++ tests/test_pthread_cooperation/main.c | 78 +++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 tests/test_pthread_cooperation/Makefile create mode 100644 tests/test_pthread_cooperation/main.c diff --git a/tests/test_pthread_cooperation/Makefile b/tests/test_pthread_cooperation/Makefile new file mode 100644 index 0000000000..2590de5206 --- /dev/null +++ b/tests/test_pthread_cooperation/Makefile @@ -0,0 +1,14 @@ +export PROJECT = test_pthread_cooperation +include ../Makefile.tests_common + +USEMODULE += posix +USEMODULE += pthread + +ifeq ($(BOARD),native) + CFLAGS += -isystem $(RIOTBASE)/sys/posix/pthread/include +else + export INCLUDES = -I$(RIOTBASE)/sys/posix/pthread/include \ + -I$(RIOTBASE)/sys/posix/include +endif + +include $(RIOTBASE)/Makefile.include diff --git a/tests/test_pthread_cooperation/main.c b/tests/test_pthread_cooperation/main.c new file mode 100644 index 0000000000..4a0d01128e --- /dev/null +++ b/tests/test_pthread_cooperation/main.c @@ -0,0 +1,78 @@ +/* + * Copyright (C) 2014 Hamburg University of Applied Sciences + * + * This file is subject to the terms and conditions of the GNU Lesser General + * Public License. See the file LICENSE in the top level directory for more + * details. + */ + +/** + * @ingroup tests + * @{ + * + * @file + * @brief pthread test application + * + * @author Raphael Hiesgen + * + * @} + */ + +#include +#include + +#define NUM_THREADS 12 + +pthread_t ths[NUM_THREADS]; + +pthread_mutex_t mtx; +volatile int storage = 1; + +void *run(void *parameter) +{ + int arg = (int) parameter; + printf("My arg: %d\n", arg); + + int err = pthread_mutex_lock(&mtx); + + if (err != 1) { + printf("[!!!] pthread_mutex_lock failed with %d\n", err); + return NULL; + } + + storage *= arg; + printf("val = %d\n", storage); + pthread_mutex_unlock(&mtx); + + return NULL; +} + +int main(void) +{ + pthread_attr_t th_attr; + pthread_attr_init(&th_attr); + pthread_mutex_init(&mtx, NULL); + + for (int i = 0; i < NUM_THREADS; ++i) { + printf("Creating thread with arg %d\n", (i + 1)); + pthread_create(&ths[i], &th_attr, run, (void *)(i + 1)); + } + + for (int i = 0; i < NUM_THREADS; ++i) { + printf("join\n"); + pthread_join(ths[i], NULL); + } + + printf("Factorial: %d\n", storage); + + if (storage != 479001600) { + puts("[!!!] Error, expected: 12!= 479001600."); + } + + pthread_mutex_destroy(&mtx); + pthread_attr_destroy(&th_attr); + + puts("finished"); + return 0; +} +