diff --git a/src/MQTTAsync.c b/src/MQTTAsync.c index 6f6caa6d..4c92eee6 100644 --- a/src/MQTTAsync.c +++ b/src/MQTTAsync.c @@ -627,8 +627,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) @@ -636,6 +634,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 8c4554ec..7126f436 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");