diff --git a/src/MQTTAsync.c b/src/MQTTAsync.c index c5516a63..50940e02 100644 --- a/src/MQTTAsync.c +++ b/src/MQTTAsync.c @@ -629,8 +629,6 @@ int MQTTAsync_connect(MQTTAsync handle, const MQTTAsync_connectOptions* options) m->connect.context = options->context; m->connectTimeout = options->connectTimeout; - MQTTAsync_tostop = 0; - /* don't lock async mutex if we are being called from a callback */ thread_id = Thread_getid(); if (thread_id != sendThread_id && thread_id != receiveThread_id) @@ -638,6 +636,7 @@ int MQTTAsync_connect(MQTTAsync handle, const MQTTAsync_connectOptions* options) MQTTAsync_lock_mutex(mqttasync_mutex); locked = 1; } + MQTTAsync_tostop = 0; if (sendThread_state != STARTING && sendThread_state != RUNNING) { sendThread_state = STARTING; diff --git a/src/MQTTAsyncUtils.c b/src/MQTTAsyncUtils.c index 11f4785d..b9dc0489 100644 --- a/src/MQTTAsyncUtils.c +++ b/src/MQTTAsyncUtils.c @@ -198,7 +198,9 @@ void MQTTAsync_terminate(void) { FUNC_ENTRY; MQTTAsync_stop(); - if (global_initialized) + + /* don't destroy global data if a new client was created while waiting for background threads to terminate */ + if (global_initialized && bstate->clients->count == 0) { ListElement* elem = NULL; ListFree(bstate->clients); @@ -2309,7 +2311,7 @@ static void MQTTAsync_stop(void) { int count = 0; MQTTAsync_tostop = 1; - while ((sendThread_state != STOPPED || receiveThread_state != STOPPED) && ++count < 100) + while ((sendThread_state != STOPPED || receiveThread_state != STOPPED) && MQTTAsync_tostop != 0 && ++count < 100) { MQTTAsync_unlock_mutex(mqttasync_mutex); Log(TRACE_MIN, -1, "sleeping");