From b2184665be066fbfee1c7672b8c0665bab16cb16 Mon Sep 17 00:00:00 2001 From: Sonja Happ Date: Fri, 13 Sep 2019 09:56:50 +0200 Subject: [PATCH] improve unthreaded implementation of MQTT node type - set cancel type of MQTT communication management thread to asynchronous - fix removing node from list in mqtt_stop - add a debug output upon invocation of pthread cancel in mqtt_type_stop - contributes to #248 --- lib/nodes/mqtt.cpp | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/lib/nodes/mqtt.cpp b/lib/nodes/mqtt.cpp index 1f0880b8d..c22b1b6c3 100644 --- a/lib/nodes/mqtt.cpp +++ b/lib/nodes/mqtt.cpp @@ -35,6 +35,13 @@ static pthread_t thread; static void * mosquitto_loop_thread(void *ctx) { int ret; + // set the cancel type of this thread to async + ret = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, nullptr); + if (ret != 0) { + error("Unable to set cancel type of MQTT communication thread to asynchronous."); + return nullptr; + } + while(true){ for (unsigned i = 0; i < vlist_length(&clients); i++) { struct node *node = (struct node *) vlist_at(&clients, i); @@ -380,14 +387,15 @@ int mqtt_stop(struct node *n) int ret; struct mqtt *m = (struct mqtt *) n->_vd; + // unregister client from global MQTT client list + // so that mosquitto loop is no longer invoked for this client + // important to do that before disconnecting from broker, otherwise, mosquitto thread will attempt to reconnect + vlist_remove(&clients, vlist_index(&clients, n)); + ret = mosquitto_disconnect(m->client); if (ret) goto mosquitto_error; - // unregister client from global MQTT client list - // so that mosquitto loop is no longer invoked for this client - vlist_remove_all(&clients, n); - ret = io_destroy(&m->io); if (ret) return ret; @@ -435,6 +443,7 @@ int mqtt_type_stop() ret = pthread_cancel(thread); if (ret) return ret; + debug( 3, "Called pthread_cancel() on MQTT communication management thread."); ret = pthread_join(thread, nullptr); if (ret) {