diff --git a/src/main.cpp b/src/main.cpp index 7541d23..33aeb30 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -46,5 +46,6 @@ int main() rtsp_thread.join(); mqtt_thread.join(); + LOG_INFO("[MAIN] Program exited cleanly."); return 0; } \ No newline at end of file diff --git a/src/mqtt_client_wrapper.cpp b/src/mqtt_client_wrapper.cpp index 561560e..fa0b7e5 100644 --- a/src/mqtt_client_wrapper.cpp +++ b/src/mqtt_client_wrapper.cpp @@ -4,7 +4,7 @@ std::shared_ptr mqtt_client; std::atomic mqtt_restart_required{false}; -static uint16_t broadcast_sequence = 0; +extern std::atomic g_running; // MQTT 回调定义 static void on_mqtt_connected() @@ -37,10 +37,10 @@ static void on_mqtt_message_received(const std::string &topic, const std::string void mqtt_client_thread_func() { - while (true) - { - const auto &cfg = g_app_config.mqtt; + const auto &cfg = g_app_config.mqtt; + while (g_running) + { mqtt_client = std::make_unique(cfg); mqtt_client->setConnectCallback(on_mqtt_connected); mqtt_client->setDisconnectCallback(on_mqtt_disconnected); @@ -48,16 +48,15 @@ void mqtt_client_thread_func() mqtt_client->connect(); - // 主线程监听重启信号 - while (!mqtt_restart_required) + while (!mqtt_restart_required && g_running) { std::this_thread::sleep_for(std::chrono::seconds(1)); } - // 需要重启 - LOG_INFO("[MQTT] Restarting client..."); - mqtt_client->disconnect(); // 可加锁 + // 需要重启或退出 + mqtt_client->disconnect(); mqtt_client.reset(); mqtt_restart_required = false; } + LOG_INFO("[MQTT] Client thread exiting."); } diff --git a/src/rtsp_manager.cpp b/src/rtsp_manager.cpp index ba86ed0..914a06c 100644 --- a/src/rtsp_manager.cpp +++ b/src/rtsp_manager.cpp @@ -60,7 +60,12 @@ void RTSPManager::stop() { if (loop) { - g_main_loop_quit(loop); // 退出 GMainLoop + // 在 loop 所在线程安全退出 + g_main_context_invoke(nullptr, [](gpointer data) -> gboolean + { + GMainLoop *loop = static_cast(data); + g_main_loop_quit(loop); + return G_SOURCE_REMOVE; }, loop); } if (server) @@ -68,11 +73,6 @@ void RTSPManager::stop() g_object_unref(server); server = nullptr; } - if (loop) - { - g_main_loop_unref(loop); - loop = nullptr; - } LOG_INFO("[RTSP] Server stopped."); }