From 5956f3b112025a186f81f8926ab7a88aadb6e2e7 Mon Sep 17 00:00:00 2001 From: Sandro Scherer Date: Tue, 8 Oct 2024 09:51:20 +0200 Subject: [PATCH] Fix potential deadlock in set_callback Signed-off-by: Sandro Scherer --- src/async_client.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/async_client.cpp b/src/async_client.cpp index 3bcb15be..41632d22 100644 --- a/src/async_client.cpp +++ b/src/async_client.cpp @@ -315,9 +315,10 @@ void async_client::remove_token(token* tok) void async_client::set_callback(callback& cb) { - guard g(lock_); - userCallback_ = &cb; - + { + guard g(lock_); + userCallback_ = &cb; + } int rc = MQTTAsync_setConnected(cli_, this, &async_client::on_connected); if (rc == MQTTASYNC_SUCCESS) { @@ -330,6 +331,7 @@ void async_client::set_callback(callback& cb) MQTTAsync_setConnected(cli_, nullptr, nullptr); if (rc != MQTTASYNC_SUCCESS) { + guard g(lock_); userCallback_ = nullptr; throw exception(rc); }