我搜索了堆栈溢出以找到与我的问题相关的答案。但我没有找到任何答案。
我有一个主线程(我的main()函数),它启动一个线程。新线程运行GMainLoop。在我的主要功能中,我通过在某些文件描述符上调用g_io_watch
来不断添加源代码。但是如果调度了事件,我会得到垃圾数据。
以下是我正在尝试的代码的一小部分:
GMainLoop *loop;
gpointer event_loop_thread(gpointer arg)
{
g_main_loop_run(loop);
g_main_loop_unref(loop);
return NULL;
}
int init()
{
loop = g_main_loop_new(NULL, FALSE);
g_thread_new(NULL, event_loop_thread, NULL);
return 0;
}
gboolean __hci_service(GIOChannel *source, GIOCondition condition, gpointer data)
{
// Doing something
return FALSE;
}
int main()
{
init();
int _adapter_id = hci_devid("hci0");
int hci_dev = hci_open_dev(_adapter_id);
GIOChannel *p_hci_io = g_io_channel_unix_new(dev_id);
GIOCondition cond = (GIOCondition)(G_IO_IN);
g_io_add_watch(p_hci_io, cond, __hci_service, NULL);
while (true);
// I will close file descriptor
return 0;
}
但是,如果我尝试使用此代码,那么一切都按预期工作:
GMainLoop *loop;
gpointer event_loop_thread(gpointer arg)
{
g_main_loop_run(loop);
g_main_loop_unref(loop);
return NULL;
}
int init()
{
loop = g_main_loop_new(NULL, FALSE);
g_thread_new(NULL, event_loop_thread, NULL);
return 0;
}
gboolean __hci_service(GIOChannel *source, GIOCondition condition, gpointer data)
{
// Doing something
return FALSE;
}
int main()
{
// init();
int _adapter_id = hci_devid("hci0");
int hci_dev = hci_open_dev(_adapter_id);
GIOChannel *p_hci_io = g_io_channel_unix_new(dev_id);
GIOCondition cond = (GIOCondition)(G_IO_IN);
g_io_add_watch(p_hci_io, cond, __hci_service, NULL);
loop = g_main_loop_new(NULL, FALSE);
g_main_loop_run(loop);
g_main_loop_unref(loop);
while (true);
// I will close file descriptor
return 0;
}
编辑:
我尝试将主线程的默认GMainContext传递给新创建的线程。看一看。告诉我我的方法是否正确。
GMainLoop *loop;
gpointer event_loop_thread(gpointer arg)
{
GMainContext *context = (GMainContext *)arg;
loop = g_main_loop_new(context, FALSE);
g_main_context_push_thread_default(context);
g_main_loop_run(loop);
g_main_loop_unref(loop);
return NULL;
}
int init()
{
g_thread_new(NULL, event_loop_thread, (gpointer)g_main_context_default());
return 0;
}
gboolean __hci_service(GIOChannel *source, GIOCondition condition, gpointer data)
{
// Doing something
return FALSE;
}
int main()
{
init();
int _adapter_id = hci_devid("hci0");
int hci_dev = hci_open_dev(_adapter_id);
GIOChannel *p_hci_io = g_io_channel_unix_new(dev_id);
GIOCondition cond = (GIOCondition)(G_IO_IN);
g_io_add_watch(p_hci_io, cond, __hci_service, NULL);
//loop = g_main_loop_new(NULL, FALSE);
//g_main_loop_run(loop);
//g_main_loop_unref(loop);
while (true);
// I will close file descriptor
return 0;
}