From abec5b82283e5f32ba41e3b9bf710566a1a8aa10 Mon Sep 17 00:00:00 2001 From: Olaf Bergmann Date: Tue, 10 Sep 2019 13:15:38 +0200 Subject: [PATCH] coap_mutex.h: Use pthread mutexes if detected by configure On systems that support pthread mutexes, stack usage can be minimized with the use of static variables. Concurrent access is protected on these systems with mutexes. Platforms that do not have pthread support must map the coap_mutex_* macros accordingly. --- include/coap2/coap_mutex.h | 51 ++++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 22 deletions(-) diff --git a/include/coap2/coap_mutex.h b/include/coap2/coap_mutex.h index 99d7d335..963a505a 100644 --- a/include/coap2/coap_mutex.h +++ b/include/coap2/coap_mutex.h @@ -2,6 +2,7 @@ * coap_mutex.h -- mutex utilities * * Copyright (C) 2019 Jon Shallow + * 2019 Olaf Bergmann * * This file is part of the CoAP library libcoap. Please see README for terms * of use. @@ -15,28 +16,14 @@ #ifndef COAP_MUTEX_H_ #define COAP_MUTEX_H_ -#if defined(RIOT_VERSION) - -#include - -typedef mutex_t coap_mutex_t; -#define COAP_MUTEX_INITIALIZER MUTEX_INIT -#define coap_mutex_lock(a) mutex_lock(a) -#define coap_mutex_trylock(a) mutex_trylock(a) -#define coap_mutex_unlock(a) mutex_unlock(a) - -#elif defined(WITH_CONTIKI) - -/* CONTIKI does not support mutex */ - -typedef int coap_mutex_t; -#define COAP_MUTEX_INITIALIZER 0 -#define coap_mutex_lock(a) *(a) = 1 -#define coap_mutex_trylock(a) *(a) = 1 -#define coap_mutex_unlock(a) *(a) = 0 - -#else /* ! RIOT_VERSION && ! WITH_CONTIKI */ +/* + * Mutexes are currently only used if there is a constrained stack, + * and large static variables (instead of the large variable being on + * the stack) need to be protected. + */ +#if COAP_CONSTRAINED_STACK +#if defined(HAVE_PTHREAD_H) && defined(HAVE_PTHREAD_MUTEX_LOCK) #include typedef pthread_mutex_t coap_mutex_t; @@ -45,6 +32,26 @@ typedef pthread_mutex_t coap_mutex_t; #define coap_mutex_trylock(a) pthread_mutex_trylock(a) #define coap_mutex_unlock(a) pthread_mutex_unlock(a) -#endif /* ! RIOT_VERSION && ! WITH_CONTIKI */ +#elif defined(RIOT_VERSION) +/* use RIOT's mutex API */ +#include + +typedef mutex_t coap_mutex_t; +#define COAP_MUTEX_INITIALIZER MUTEX_INIT +#define coap_mutex_lock(a) mutex_lock(a) +#define coap_mutex_trylock(a) mutex_trylock(a) +#define coap_mutex_unlock(a) mutex_unlock(a) + +#else +/* define stub mutex functions */ +typedef int coap_mutex_t; +#define COAP_MUTEX_INITIALIZER 0 +#define coap_mutex_lock(a) *(a) = 1 +#define coap_mutex_trylock(a) *(a) = 1 +#define coap_mutex_unlock(a) *(a) = 0 + +#endif /* !RIOT_VERSION && !HAVE_PTHREAD_H && !HAVE_PTHREAD_MUTEX_LOCK */ + +#endif /* COAP_CONSTRAINED_STACK */ #endif /* COAP_MUTEX_H_ */