Add multi-threaded behavior

This commit is contained in:
2025-01-16 14:57:27 +01:00
parent a5a3f5579a
commit e3873bf6ec
6 changed files with 14 additions and 6 deletions
+1
View File
@@ -0,0 +1 @@
../../CTPL
+2 -2
View File
@@ -4,8 +4,8 @@
namespace MQTT { namespace MQTT {
MQTT::MQTT(const std::string& hostname, int port) : MQTT::MQTT(const std::string& hostname, int port, int threads) :
m_pMQTTImpl(new MQTTImpl(hostname, port)) m_pMQTTImpl(new MQTTImpl(hostname, port, threads))
{ {
} }
+5 -1
View File
@@ -7,7 +7,8 @@
namespace MQTT { namespace MQTT {
MQTTImpl::MQTTImpl(const std::string& hostname, int port) : MQTTImpl::MQTTImpl(const std::string& hostname, int port, int threads) :
m_threadPool(threads),
m_hostname(hostname), m_hostname(hostname),
m_port(port), m_port(port),
m_connected(false), m_connected(false),
@@ -26,6 +27,7 @@ MQTTImpl::MQTTImpl(const std::string& hostname, int port) :
MQTTImpl::~MQTTImpl() MQTTImpl::~MQTTImpl()
{ {
m_threadPool.stop();
StopLoop(); StopLoop();
Disconnect(); Disconnect();
mosquitto_destroy(m_pMosquitto); mosquitto_destroy(m_pMosquitto);
@@ -160,7 +162,9 @@ void MQTTImpl::MessageCallback(const mosquitto_message* pMessage)
message.topic = std::string(pMessage->topic); message.topic = std::string(pMessage->topic);
message.payload = std::string(static_cast<char*>(pMessage->payload), pMessage->payloadlen); message.payload = std::string(static_cast<char*>(pMessage->payload), pMessage->payloadlen);
m_threadPool.push([this, message](int) {
m_signal.emit(message); m_signal.emit(message);
});
} }
bool MQTTImpl::InternalSubscribe(const std::string& topic) bool MQTTImpl::InternalSubscribe(const std::string& topic)
+3 -1
View File
@@ -3,6 +3,7 @@
#include "MQTT.h" #include "MQTT.h"
#include "MQTTMessage.h" #include "MQTTMessage.h"
#include <ctpl_stl.h>
#include <SimpleSignal.h> #include <SimpleSignal.h>
#include <mutex> #include <mutex>
#include <string> #include <string>
@@ -18,7 +19,7 @@ namespace MQTT {
class MQTTImpl class MQTTImpl
{ {
public: public:
MQTTImpl(const std::string& hostname, int port); MQTTImpl(const std::string& hostname, int port, int threads);
~MQTTImpl(); ~MQTTImpl();
bool Send(const MQTTMessage& message); bool Send(const MQTTMessage& message);
@@ -52,6 +53,7 @@ private:
private: private:
std::thread m_thread; std::thread m_thread;
mutable std::mutex m_mutex; mutable std::mutex m_mutex;
ctpl::thread_pool m_threadPool;
std::string m_hostname; std::string m_hostname;
int m_port; int m_port;
+1
View File
@@ -4,6 +4,7 @@
LIBRARIES += Logging LIBRARIES += Logging
CFLAGS += -I$(ROOTPATH)/Libraries/CTPL
CFLAGS += -I$(ROOTPATH)/Libraries/SimpleSignal CFLAGS += -I$(ROOTPATH)/Libraries/SimpleSignal
DEBUGDIR := .debug DEBUGDIR := .debug
+1 -1
View File
@@ -14,7 +14,7 @@ class MQTTImpl;
class MQTT class MQTT
{ {
public: public:
MQTT(const std::string& hostname, int port); MQTT(const std::string& hostname, int port, int threads = 3);
~MQTT(); ~MQTT();
MQTT(const MQTT&) = delete; MQTT(const MQTT&) = delete;