From 49d71f2bd9df50b2da80cce96e59b85b0a801756 Mon Sep 17 00:00:00 2001 From: "Roger A. Light" Date: Sun, 23 Nov 2025 23:11:56 +0000 Subject: [PATCH] Simplify stopping the thread in libmosquitto --- lib/loop.c | 12 ++++++------ lib/mosquitto_internal.h | 1 + lib/thread_mosq.c | 1 + 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/lib/loop.c b/lib/loop.c index d3d2740a..36f9b839 100644 --- a/lib/loop.c +++ b/lib/loop.c @@ -243,7 +243,6 @@ static int interruptible_sleep(struct mosquitto *mosq, time_t reconnect_delay) int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, int max_packets) { - int run = 1; int rc = MOSQ_ERR_SUCCESS; unsigned long reconnect_delay; @@ -252,14 +251,15 @@ int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, int max_packets) } mosq->reconnects = 0; + mosq->run = true; - while(run){ + while(mosq->run){ do{ #ifdef HAVE_PTHREAD_CANCEL COMPAT_pthread_testcancel(); #endif rc = mosquitto_loop(mosq, timeout, max_packets); - }while(run && rc == MOSQ_ERR_SUCCESS); + }while(mosq->run && rc == MOSQ_ERR_SUCCESS); /* Quit after fatal errors. */ switch(rc){ case MOSQ_ERR_NOMEM: @@ -287,7 +287,7 @@ int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, int max_packets) #endif rc = MOSQ_ERR_SUCCESS; if(mosquitto__get_request_disconnect(mosq)){ - run = 0; + mosq->run = false; }else{ if(mosq->reconnect_delay_max > mosq->reconnect_delay){ if(mosq->reconnect_exponential_backoff){ @@ -311,12 +311,12 @@ int mosquitto_loop_forever(struct mosquitto *mosq, int timeout, int max_packets) } if(mosquitto__get_request_disconnect(mosq)){ - run = 0; + mosq->run = false; }else{ rc = mosquitto_reconnect(mosq); } } - }while(run && rc != MOSQ_ERR_SUCCESS); + }while(mosq->run && rc != MOSQ_ERR_SUCCESS); } return rc; } diff --git a/lib/mosquitto_internal.h b/lib/mosquitto_internal.h index fe417c5d..3ec9df7f 100644 --- a/lib/mosquitto_internal.h +++ b/lib/mosquitto_internal.h @@ -360,6 +360,7 @@ struct mosquitto { enum mosquitto__keyform tls_keyform; #endif bool want_write; + bool run; #if defined(WITH_THREADING) && !defined(WITH_BROKER) pthread_mutex_t callback_mutex; pthread_mutex_t log_callback_mutex; diff --git a/lib/thread_mosq.c b/lib/thread_mosq.c index 2e08ec48..931bf9eb 100644 --- a/lib/thread_mosq.c +++ b/lib/thread_mosq.c @@ -79,6 +79,7 @@ int mosquitto_loop_stop(struct mosquitto *mosq, bool force) return MOSQ_ERR_INVAL; } + mosq->run = false; /* Write a single byte to sockpairW (connected to sockpairR) to break out * of select() if in threaded mode. */