eclipse / mosquitto

Eclipse Mosquitto - An open source MQTT broker
https://mosquitto.org
Other
8.93k stars 2.37k forks source link

mosquitto loop_forever crash sometimes when using disconnect method #2007

Open yonatansalton opened 3 years ago

yonatansalton commented 3 years ago

Hi, I'm using the latest mosquittopp wrapper for c++. Sometimes when i'm using the disconnect method, it seems that loop_forever crashes. On the output I get Critical error detected c0000374 Unhandled exception at 0x00007FF9FA9B9059 (ntdll.dll) in xxxxx.exe: 0xC0000374: A heap has been corrupted (parameters: 0x00007FF9FAA227F0).

ralight commented 3 years ago

Could you please provide a minimised version of your code that reproduces this error?

yonatansalton commented 3 years ago

// Connection part: m_rnd_id = QUuid::createUuid().toString(); m_mosq = new mosquittopp (m_rnd_id , true) m_mosq->connect_async(IPv4Add, IPv4PortVal, 5); m_mosq->subscribe(&mid, topic, 2)

// create the forever loop function: m_t = std::thread(&MainWindow::mosquitto_loop_func, this);

// mosquitto_loop_func: void MainWindow::mosquitto_loop_func() { int rc = m_mosq->loop_forever(1000, 1); }

Up to here everything works fine, I'm able to publish messages and receive messages from subscribed topics. The problem start here sometimes when I try to disconnect like that:

m_mosq->disconnect();

Sometimes it works, sometime it crashes.

ralight commented 3 years ago

Please either use mosquitto_loop_start(), this will do exactly what you are doing with your thread, or else mosquitto_threaded_set(mosq, true) to tell the library that you are using threads.

yonatansalton commented 3 years ago

mosquitto_loop_start doesn't seem to work for some reason, and when I set the mosquitto_threaded_set to true it still crashes sometimes.. any other ideas?

ralight commented 3 years ago

Ah, I noticed you're on Windows. The library isn't compiled with threading support on Windows so actually it's not a surprise there's a problem. The solution is to recompile with pthread support. Pthreads on Windows is awkward in lots of ways, which is why it isn't provided as part of the project supplied binaries, so this isn't a very satisfactory answer.

yonatansalton commented 3 years ago

Hi, The first option you gave handling the threading myself using loop_forever and mosquitto_threaded_set(mosq,true) didn't worked for me and still got a crash every once in a while.

The second option compiling the mosquitto with pthreads support works great. Thanks a lot !

ralight commented 3 years ago

mosquitto_threaded_set(mosq,true) wouldn't have provided any benefit without threading support compiled in. If you're using your own thread please do set it as well.