我正在尝试创建一个自定义GMainContext*
(以免与 Qt/etc 冲突)并在自定义线程上处理循环。
我正在使用libnm
(用于 NetworkManager),但我认为它不相关。
使用自定义GMainContext*
.
#include <NetworkManager.h>
#include <iostream>
#include <thread>
// Uncomment this for it to not work.
#define WORKING
static void test_callback ()
{
std::cerr << "test callback";
}
static int thread(GMainContext *mainContext)
{
GMainLoop* mainLoop = g_main_loop_new(mainContext, FALSE);
g_main_loop_run(mainLoop);
}
int main(int argc, char *argv[])
{
#ifdef WORKING
GMainContext* mainContext = g_main_context_default();
#else
GMainContext* mainContext = g_main_context_new();
g_main_context_push_thread_default(mainContext);
#endif
GError* error = nullptr;
NMClient* client = nm_client_new(nullptr, &error);
g_signal_connect(client, NM_CLIENT_ACTIVE_CONNECTION_ADDED, G_CALLBACK(test_callback), nullptr);
g_signal_connect(client, NM_CLIENT_ACTIVE_CONNECTION_REMOVED, G_CALLBACK(test_callback), nullptr);
std::thread thread_obj(thread, mainContext);
thread_obj.join();
return 0;
}
信号处理程序使用已WORKING
定义的正确引发,使用g_main_context_default()
.