Threads: Support multiple threads doing coap_io_process()

Set up a coap_io_process() loop spread across multiple threads, each thread
repeatably calling coap_io_process() and so able to handle any input packets.

Note that the application handlers need to be thread-safe for application
level activity.

Add 2 new main functions
  coap_io_process_loop()
  coap_io_process_terminate_loop()

Add in 2 new sub functions
  coap_io_process_configure_threads()
  coap_io_process_remove_threads()
to set up the parallel threads.

Update example servers to include using coap_io_process_loop().

Support optional thread number logging by configuration to maintain
backwards logging format output if required.
This commit is contained in:
Jon Shallow authored and Jon Shallow committed 2025-03-19 09:18:35 +00:00
1 parent 0ba446d788
commit cce7b65398
27 files changed
+947 -46

No files matched your search

+32 -2
View File
@@ -784,7 +784,7 @@ void
coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu) {
#if COAP_CONSTRAINED_STACK
/* Proxy-Uri: can be 1034 bytes long */
/* buf and outbuf can be protected by global_lock if needed */
/* buf and outbuf can be protected by m_show_pdu if needed */
static unsigned char buf[min(COAP_DEBUG_BUF_SIZE, 1035)];
static char outbuf[COAP_DEBUG_BUF_SIZE];
#else /* ! COAP_CONSTRAINED_STACK */
@@ -809,6 +809,9 @@ coap_show_pdu(coap_log_t level, const coap_pdu_t *pdu) {
if (level > coap_get_log_level())
return;
#if COAP_THREAD_SAFE
coap_mutex_lock(&m_show_pdu);
#endif /* COAP_THREAD_SAFE */
if (!pdu->session || COAP_PROTO_NOT_RELIABLE(pdu->session->proto)) {
snprintf(outbuf, sizeof(outbuf), "v:%d t:%s c:%s i:%04x {",
COAP_DEFAULT_VERSION, msg_type_string(pdu->type),
@@ -1055,6 +1058,9 @@ no_more:
snprintf(&outbuf[outbuflen], sizeof(outbuf)-outbuflen,
"data length %zu (data suppressed)\n", data_len);
COAP_DO_SHOW_OUTPUT_LINE;
#if COAP_THREAD_SAFE
coap_mutex_unlock(&m_show_pdu);
#endif /* COAP_THREAD_SAFE */
return;
}
@@ -1130,6 +1136,10 @@ no_more:
outbuflen--;
snprintf(&outbuf[outbuflen], sizeof(outbuf)-outbuflen, "\n");
COAP_DO_SHOW_OUTPUT_LINE;
#if COAP_THREAD_SAFE
coap_mutex_unlock(&m_show_pdu);
#endif /* COAP_THREAD_SAFE */
}
void
@@ -1278,12 +1288,21 @@ coap_set_log_handler(coap_log_handler_t handler) {
log_handler = handler;
}
/* Visible to only this thread */
extern COAP_THREAD_LOCAL_VAR uint32_t thread_no;
/* Visible across all threads */
extern uint32_t max_thread_no;
void
coap_log_impl(coap_log_t level, const char *format, ...) {
#if COAP_THREAD_SAFE
coap_mutex_lock(&m_log_impl);
#endif /* COAP_THREAD_SAFE */
if (log_handler) {
#if COAP_CONSTRAINED_STACK
/* message can be protected by global_lock if needed */
/* message can be protected by m_log_impl if needed */
static char message[COAP_DEBUG_BUF_SIZE];
#else /* ! COAP_CONSTRAINED_STACK */
char message[COAP_DEBUG_BUF_SIZE];
@@ -1312,6 +1331,13 @@ coap_log_impl(coap_log_t level, const char *format, ...) {
if (len)
fprintf(log_fd, "%.*s ", (int)len, timebuf);
#if COAP_THREAD_NUM_LOGGING
if (thread_no == 0) {
thread_no = ++max_thread_no;
}
fprintf(log_fd, "%2d ", thread_no);
#endif /* COAP_THREAD_NUM_LOGGING */
fprintf(log_fd, "%s ", coap_log_level_desc(level));
va_start(ap, format);
@@ -1323,6 +1349,10 @@ coap_log_impl(coap_log_t level, const char *format, ...) {
va_end(ap);
fflush(log_fd);
}
#if COAP_THREAD_SAFE
coap_mutex_unlock(&m_log_impl);
#endif /* COAP_THREAD_SAFE */
}
static struct packet_num_interval {
+224 -12
View File
@@ -1777,6 +1777,81 @@ coap_io_process_with_fds(coap_context_t *ctx, uint32_t timeout_ms,
return ret;
}
#if !defined(COAP_EPOLL_SUPPORT) && COAP_THREAD_SAFE
static unsigned int
coap_io_prepare_fds(coap_context_t *ctx,
int enfds, fd_set *ereadfds, fd_set *ewritefds,
fd_set *eexceptfds) {
coap_session_t *s, *stmp;
unsigned int max_sockets = sizeof(ctx->sockets) / sizeof(ctx->sockets[0]);
coap_fd_t nfds = 0;
unsigned int i;
ctx->num_sockets = 0;
#if COAP_SERVER_SUPPORT
coap_endpoint_t *ep;
LL_FOREACH(ctx->endpoint, ep) {
if (ep->sock.flags & (COAP_SOCKET_WANT_READ | COAP_SOCKET_WANT_WRITE | COAP_SOCKET_WANT_ACCEPT)) {
if (ctx->num_sockets < max_sockets)
ctx->sockets[ctx->num_sockets++] = &ep->sock;
}
SESSIONS_ITER(ep->sessions, s, stmp) {
if (s->sock.flags & (COAP_SOCKET_WANT_READ|COAP_SOCKET_WANT_WRITE)) {
if (ctx->num_sockets < max_sockets)
ctx->sockets[ctx->num_sockets++] = &s->sock;
}
}
}
#endif /* COAP_SERVER_SUPPORT */
#if COAP_CLIENT_SUPPORT
SESSIONS_ITER(ctx->sessions, s, stmp) {
if (s->sock.flags & (COAP_SOCKET_WANT_READ |
COAP_SOCKET_WANT_WRITE |
COAP_SOCKET_WANT_CONNECT)) {
if (ctx->num_sockets < max_sockets)
ctx->sockets[ctx->num_sockets++] = &s->sock;
}
}
#endif /* COAP_CLIENT_SUPPORT */
if (ereadfds) {
ctx->readfds = *ereadfds;
nfds = enfds;
} else {
FD_ZERO(&ctx->readfds);
}
if (ewritefds) {
ctx->writefds = *ewritefds;
nfds = enfds;
} else {
FD_ZERO(&ctx->writefds);
}
if (eexceptfds) {
ctx->exceptfds = *eexceptfds;
nfds = enfds;
} else {
FD_ZERO(&ctx->exceptfds);
}
for (i = 0; i < ctx->num_sockets; i++) {
if (ctx->sockets[i]->fd + 1 > nfds)
nfds = ctx->sockets[i]->fd + 1;
if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ)
FD_SET(ctx->sockets[i]->fd, &ctx->readfds);
if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_WRITE)
FD_SET(ctx->sockets[i]->fd, &ctx->writefds);
#if !COAP_DISABLE_TCP
if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_ACCEPT)
FD_SET(ctx->sockets[i]->fd, &ctx->readfds);
if (ctx->sockets[i]->flags & COAP_SOCKET_WANT_CONNECT) {
FD_SET(ctx->sockets[i]->fd, &ctx->writefds);
FD_SET(ctx->sockets[i]->fd, &ctx->exceptfds);
}
#endif /* !COAP_DISABLE_TCP */
}
return nfds;
}
#endif /* ! COAP_EPOLL_SUPPORT && COAP_THREAD_SAFE */
int
coap_io_process_with_fds_lkd(coap_context_t *ctx, uint32_t timeout_ms,
int enfds, fd_set *ereadfds, fd_set *ewritefds,
@@ -1858,7 +1933,7 @@ coap_io_process_with_fds_lkd(coap_context_t *ctx, uint32_t timeout_ms,
coap_lock_lock(ctx, return -1);
} else {
result = 0;
goto all_over;
}
if (result < 0) { /* error */
@@ -1866,10 +1941,38 @@ coap_io_process_with_fds_lkd(coap_context_t *ctx, uint32_t timeout_ms,
coap_win_error_to_errno();
#endif
if (errno != EINTR) {
coap_log_err("select: %s", coap_socket_strerror());
#if COAP_THREAD_SAFE
if (errno == EBADF) {
coap_log_debug("select: %s\n", coap_socket_strerror());
goto all_over;
}
#endif /* COAP_THREAD_SAFE */
coap_log_err("select: %s\n", coap_socket_strerror());
return -1;
}
goto all_over;
}
#if COAP_THREAD_SAFE
/* Need to refresh what is available to read / write etc. */
nfds = coap_io_prepare_fds(ctx, enfds, ereadfds, ewritefds, eexceptfds);
tv.tv_usec = 0;
tv.tv_sec = 0;
result = select((int)nfds, &ctx->readfds, &ctx->writefds, &ctx->exceptfds, &tv);
if (result < 0) { /* error */
#ifdef _WIN32
coap_win_error_to_errno();
#endif
if (errno != EINTR) {
if (errno == EBADF) {
coap_log_debug("select: %s\n", coap_socket_strerror());
goto all_over;
}
coap_log_err("select: %s\n", coap_socket_strerror());
return -1;
}
goto all_over;
}
#endif /* COAP_THREAD_SAFE */
if (ereadfds) {
*ereadfds = ctx->readfds;
}
@@ -1881,12 +1984,6 @@ coap_io_process_with_fds_lkd(coap_context_t *ctx, uint32_t timeout_ms,
}
if (result > 0) {
#if COAP_THREAD_SAFE
/* Need to refresh what is available to read / write etc. */
tv.tv_usec = 0;
tv.tv_sec = 0;
select((int)nfds, &ctx->readfds, &ctx->writefds, &ctx->exceptfds, &tv);
#endif /* COAP_THREAD_SAFE */
for (i = 0; i < ctx->num_sockets; i++) {
if ((ctx->sockets[i]->flags & COAP_SOCKET_WANT_READ) &&
FD_ISSET(ctx->sockets[i]->fd, &ctx->readfds))
@@ -1962,6 +2059,7 @@ coap_io_process_with_fds_lkd(coap_context_t *ctx, uint32_t timeout_ms,
break;
}
coap_lock_lock(ctx, return -1);
#if COAP_THREAD_SAFE
/* Need to refresh what is available to read / write etc. */
nfds = epoll_wait(ctx->epfd, events, COAP_MAX_EPOLL_EVENTS, 0);
@@ -1970,11 +2068,9 @@ coap_io_process_with_fds_lkd(coap_context_t *ctx, uint32_t timeout_ms,
coap_log_err("epoll_wait: unexpected error: %s (%d)\n",
coap_socket_strerror(), nfds);
}
coap_lock_lock(ctx, return -1);
break;
}
#endif /* COAP_THREAD_SAFE */
coap_lock_lock(ctx, return -1);
coap_io_do_epoll_lkd(ctx, events, nfds);
@@ -1992,16 +2088,132 @@ coap_io_process_with_fds_lkd(coap_context_t *ctx, uint32_t timeout_ms,
#if COAP_SERVER_SUPPORT
coap_expire_cache_entries(ctx);
#endif /* COAP_SERVER_SUPPORT */
coap_ticks(&now);
#if COAP_ASYNC_SUPPORT
/* Check to see if we need to send off any Async requests as delay might
have been updated */
coap_check_async(ctx, now);
coap_ticks(&now);
coap_check_async(ctx, now);
#endif /* COAP_ASYNC_SUPPORT */
#ifndef COAP_EPOLL_SUPPORT
all_over:
#endif /* COAP_EPOLL_SUPPORT */
coap_ticks(&now);
return (int)(((now - before) * 1000) / COAP_TICKS_PER_SECOND);
}
volatile int coap_thread_quit = 0;
void
coap_io_process_terminate_loop(void) {
coap_send_recv_terminate();
coap_thread_quit = 1;
}
COAP_API int
coap_io_process_loop(coap_context_t *context,
coap_io_process_thread_t main_loop_code,
void *main_loop_code_arg, uint32_t timeout_ms,
uint32_t thread_count) {
int ret;
if (!context)
return 0;
coap_lock_lock(context, return 0);
ret = coap_io_process_loop_lkd(context, main_loop_code,
main_loop_code_arg, timeout_ms,
thread_count);
coap_lock_unlock(context);
return ret;
}
int
coap_io_process_loop_lkd(coap_context_t *context,
coap_io_process_thread_t main_loop_code,
void *main_loop_code_arg, uint32_t timeout_ms,
uint32_t thread_count) {
int ret = 0;;
#if COAP_THREAD_SAFE
if (thread_count > 1) {
if (!coap_io_process_configure_threads(context, thread_count - 1))
return 0;
}
#else /* COAP_THREAD_SAFE */
thread_count = 1;
#endif /* COAP_THREAD_SAFE */
while (!coap_thread_quit) {
if (main_loop_code) {
coap_tick_t begin, end;
uint32_t used_ms;
coap_ticks(&begin);
/*
* main_loop_codecode should not be blocking for any time, and not calling
* coap_io_process().
*/
coap_lock_callback_release(context, main_loop_code(main_loop_code_arg),
/* On re-lock failure */
ret = 0; break);
/*
* Need to delay for the remainder of timeout_ms. In case main_loop_code()
* is time sensitive (e.g Observe subscription to /time), delay to the
* start of the a second boundary
*/
coap_ticks(&end);
used_ms = (uint32_t)(end - begin) * 1000 / COAP_TICKS_PER_SECOND;
if (timeout_ms == COAP_IO_NO_WAIT || timeout_ms == COAP_IO_WAIT) {
ret = coap_io_process_lkd(context, timeout_ms);
} else if (timeout_ms > used_ms) {
/* Wait for remaining time rounded up to next second start */
coap_tick_t next_time = end + (timeout_ms - used_ms) * COAP_TICKS_PER_SECOND / 1000;
unsigned int next_sec_us;
unsigned int next_sec_ms;
next_sec_us = (timeout_ms - used_ms) * 1000000 / COAP_TICKS_PER_SECOND + 1000000 -
(coap_ticks_to_rt_us(next_time) % 1000000);
next_sec_ms = (next_sec_us + 999) / 1000;
if (next_sec_ms > timeout_ms && next_sec_ms > 1000)
next_sec_ms -= 1000;
ret = coap_io_process_lkd(context, next_sec_ms ? next_sec_ms : 1);
} else {
/* timeout_ms has expired */
ret = coap_io_process_lkd(context, COAP_IO_NO_WAIT);
}
if (thread_count == 1) {
/*
* Need to delay if only one thread until the remainder of
* timeout_ms is used up. Otherwise, another thread will be
* waiting on coap_io_process() to do any input / timeout work.
*/
coap_ticks(&end);
used_ms = (uint32_t)(end - begin) * 1000 / COAP_TICKS_PER_SECOND;
if (timeout_ms > 0 && timeout_ms < used_ms) {
ret = coap_io_process_lkd(context, used_ms - timeout_ms);
} else {
ret = coap_io_process_lkd(context, COAP_IO_NO_WAIT);
}
}
} else {
ret = coap_io_process_lkd(context, timeout_ms);
}
/* coap_io_process_lkd() can return 0 */
if (ret >= 0)
ret = 1;
if (ret < 0) {
ret = 0;
break;
}
}
#if COAP_THREAD_SAFE
coap_io_process_remove_threads(context);
#endif /* COAP_THREAD_SAFE */
coap_thread_quit = 0;
return ret;
}
#endif /* ! WITH_LWIP && ! WITH_CONTIKI && ! RIOT_VERSION*/
COAP_API int
+17
View File
@@ -2500,11 +2500,13 @@ coap_read_endpoint(coap_context_t *ctx, coap_endpoint_t *endpoint, coap_tick_t n
} else if (bytes_read > 0) {
coap_session_t *session = coap_endpoint_get_session(endpoint, packet, now);
if (session) {
coap_session_reference_lkd(session);
coap_log_debug("* %s: netif: recv %4zd bytes\n",
coap_session_str(session), bytes_read);
result = coap_handle_dgram_for_proto(ctx, session, packet);
if (endpoint->proto == COAP_PROTO_DTLS && session->type == COAP_SESSION_TYPE_HELLO && result == 1)
coap_session_new_dtls_session(session, now);
coap_session_release_lkd(session);
}
}
return result;
@@ -4793,6 +4795,12 @@ int coap_started = 0;
* Global lock for multi-thread support
*/
coap_lock_t global_lock;
/*
* low level protection mutex
*/
coap_mutex_t m_show_pdu;
coap_mutex_t m_log_impl;
coap_mutex_t m_io_threads;
#endif /* COAP_THREAD_SAFE */
void
@@ -4808,6 +4816,9 @@ coap_startup(void) {
#if COAP_THREAD_SAFE
coap_lock_init();
coap_mutex_init(&m_show_pdu);
coap_mutex_init(&m_log_impl);
coap_mutex_init(&m_io_threads);
#endif /* COAP_THREAD_SAFE */
#if defined(HAVE_WINSOCK2_H)
@@ -4856,6 +4867,12 @@ coap_cleanup(void) {
#endif /* WITH_LWIP */
coap_dtls_shutdown();
#if COAP_THREAD_SAFE
coap_mutex_destroy(&m_show_pdu);
coap_mutex_destroy(&m_log_impl);
coap_mutex_destroy(&m_io_threads);
#endif /* COAP_THREAD_SAFE */
coap_debug_reset();
}
+6 -4
View File
@@ -105,10 +105,12 @@ coap_netif_dgrm_read_ep(coap_endpoint_t *endpoint, coap_packet_t *packet) {
bytes_read = coap_socket_recv(&endpoint->sock, packet);
keep_errno = errno;
if (bytes_read == -1) {
coap_log_debug("* %s: netif: failed to read %zd bytes (%s)\n",
coap_endpoint_str(endpoint), packet->length,
coap_socket_strerror());
errno = keep_errno;
if (errno != EAGAIN) {
coap_log_debug("* %s: netif: failed to read %zd bytes (%s)\n",
coap_endpoint_str(endpoint), packet->length,
coap_socket_strerror());
errno = keep_errno;
}
} else if (bytes_read > 0) {
/* Let the caller do the logging as session available by then */
}
+1 -1
View File
@@ -1343,7 +1343,7 @@ coap_resource_notify_observers_lkd(coap_resource_t *r,
}
r->context->observe_pending = 1;
coap_update_io_timer(r->context, 0);
coap_check_notify_lkd(r->context);
return 1;
}
+1 -1
View File
@@ -1433,8 +1433,8 @@ coap_session_create_client(coap_context_t *ctx,
#endif /* !COAP_DISABLE_TCP */
}
#ifdef COAP_EPOLL_SUPPORT
session->sock.session = session;
#ifdef COAP_EPOLL_SUPPORT
coap_epoll_ctl_add(&session->sock,
EPOLLIN |
((session->sock.flags & COAP_SOCKET_WANT_CONNECT) ?
+6 -4
View File
@@ -300,16 +300,18 @@ coap_socket_accept_tcp(coap_socket_t *server,
#endif
(void)extra;
server->flags &= ~COAP_SOCKET_CAN_ACCEPT;
new_client->fd = accept(server->fd, &remote_addr->addr.sa,
&remote_addr->size);
if (new_client->fd == COAP_INVALID_SOCKET) {
coap_log_warn("coap_socket_accept_tcp: accept: %s\n",
coap_socket_strerror());
if (errno != EAGAIN) {
coap_log_warn("coap_socket_accept_tcp: accept: %s\n",
coap_socket_strerror());
}
return 0;
}
server->flags &= ~COAP_SOCKET_CAN_ACCEPT;
if (getsockname(new_client->fd, &local_addr->addr.sa, &local_addr->size) < 0)
coap_log_warn("coap_socket_accept_tcp: getsockname: %s\n",
coap_socket_strerror());
+106
View File
@@ -99,6 +99,112 @@ coap_lock_lock_func(void) {
}
#endif /* ! COAP_THREAD_RECURSIVE_CHECK */
#if !WITH_LWIP
extern volatile int coap_thread_quit;
static pthread_t *thread_id = NULL;
static uint32_t thread_id_count = 0;
/* Visible to only this thread */
COAP_THREAD_LOCAL_VAR uint32_t thread_no = 0;
/* Visible across all threads */
uint32_t max_thread_no = 0;
typedef struct {
coap_context_t *context;
uint32_t thread_no;
} coap_thread_param_t;
static void *
coap_io_process_worker_thread(void *arg) {
coap_thread_param_t *thread_param = (coap_thread_param_t *)arg;
coap_context_t *context = thread_param->context;
thread_no = thread_param->thread_no;
coap_free_type(COAP_STRING, thread_param);
coap_log_debug("Thread %lx start\n", pthread_self());
while (!coap_thread_quit) {
int result;
coap_lock_lock(context, return 0);
result = coap_io_process_lkd(context, COAP_IO_WAIT);
coap_lock_unlock(context);
if (result < 0)
break;
}
coap_log_debug("Thread %lx exit\n", pthread_self());
return 0;
}
int
coap_io_process_configure_threads(coap_context_t *context, uint32_t thread_count) {
uint32_t i;
coap_mutex_lock(&m_io_threads);
thread_no = 1;
max_thread_no = 1 + thread_count;
coap_free_type(COAP_STRING, thread_id);
thread_id = coap_malloc_type(COAP_STRING, thread_count * sizeof(pthread_t));
if (!thread_id) {
coap_log_err("thread start up memory allocate failure\n");
coap_mutex_unlock(&m_io_threads);
return 0;
}
for (i = 0; i < thread_count ; i++) {
coap_thread_param_t *thread_param = coap_malloc_type(COAP_STRING, sizeof(coap_thread_param_t));
int s;
thread_param->context = context;
thread_param->thread_no = i + 2;
s = pthread_create(&thread_id[i], NULL,
&coap_io_process_worker_thread, thread_param);
if (s != 0) {
coap_log_err("thread start up failure (%s)\n", coap_socket_strerror());
coap_mutex_unlock(&m_io_threads);
return 0;
}
thread_id_count++;
}
coap_mutex_unlock(&m_io_threads);
return 1;
}
#ifdef HAVE_SIGNAL_H
#include <signal.h>
#endif /* HAVE_SIGNAL_H */
void
coap_io_process_remove_threads(coap_context_t *context) {
uint32_t i;
(void)context;
coap_lock_unlock(context);
coap_mutex_lock(&m_io_threads);
for (i = 0; i < thread_id_count ; i++) {
int s = pthread_kill(thread_id[i], SIGINT);
if (s != 0) {
coap_log_err("thread kill failure\n");
}
}
for (i = 0; i < thread_id_count ; i++) {
void *retval;
int s = pthread_join(thread_id[i], &retval);
if (s != 0) {
coap_log_err("thread join failure\n");
}
}
coap_free_type(COAP_STRING, thread_id);
thread_id = NULL;
thread_id_count = 0;
coap_mutex_unlock(&m_io_threads);
coap_lock_lock(context, return);
}
#endif /* !WITH_LWIP */
#else /* ! COAP_THREAD_SAFE */
#ifdef __clang__