From 63c5077cf0b87750472b8b33ed35c62ea8925e04 Mon Sep 17 00:00:00 2001 From: Jon Shallow Date: Thu, 20 Jun 2024 11:29:12 +0100 Subject: [PATCH] coap_cleanup: Support multiple usage --- man/coap_init.txt.in | 8 ++++++-- src/coap_net.c | 4 +++- src/coap_threadsafe.c | 8 ++++---- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/man/coap_init.txt.in b/man/coap_init.txt.in index 4a92977e..91569679 100644 --- a/man/coap_init.txt.in +++ b/man/coap_init.txt.in @@ -55,8 +55,12 @@ until *coap_cleanup*() is called. The *coap_cleanup*() function is used to cleanup / free any information set up by the *coap_startup*() function and should be the last *coap_**() function -called. It is possible to call *coap_startup*() after *coap_cleanup*() to -re-initialize the libcoap logic. +called. The only safe function that can be called after *coap_cleanup*() is +*coap_startup*() to re-initialize the libcoap logic. + +*NOTE:* Calling *coap_cleanup*() in one thread while continuing to use other +*coap_**() function calls in a different thread is not supported - even if they +are using a different coap_context_t. *NOTE:* All other libcoap cleanups should called prior to *coap_cleanup*(), e.g. *coap_free_context*(3). diff --git a/src/coap_net.c b/src/coap_net.c index 88715137..dc36714c 100644 --- a/src/coap_net.c +++ b/src/coap_net.c @@ -4453,6 +4453,9 @@ coap_startup(void) { void coap_cleanup(void) { + if (!coap_started) + return; + coap_started = 0; #if defined(HAVE_WINSOCK2_H) WSACleanup(); #elif defined(WITH_CONTIKI) @@ -4469,7 +4472,6 @@ coap_cleanup(void) { coap_mutex_destroy(&m_persist_add); #endif /* COAP_CONSTRAINED_STACK */ coap_debug_reset(); - coap_started = 0; } void diff --git a/src/coap_threadsafe.c b/src/coap_threadsafe.c index 9b751c49..0a723d8c 100644 --- a/src/coap_threadsafe.c +++ b/src/coap_threadsafe.c @@ -33,8 +33,8 @@ coap_lock_unlock_func(coap_lock_t *lock, const char *file, int line) { int coap_lock_lock_func(coap_lock_t *lock, int force, const char *file, int line) { - if (!force && lock->being_freed) { - /* context is going away */ + if ((!force && lock->being_freed) || !coap_started) { + /* context is going away or libcoap not initialized with coap_startup() */ return 0; } if (coap_mutex_trylock(&lock->mutex)) { @@ -88,8 +88,8 @@ coap_lock_unlock_func(coap_lock_t *lock) { int coap_lock_lock_func(coap_lock_t *lock, int force) { - if (!force && lock->being_freed) { - /* context is going away */ + if ((!force && lock->being_freed) || !coap_started) { + /* context is going away or libcoap not initialized with coap_startup() */ return 0; } /*