我已经搜查堆栈溢出找到有关我的问题的答案。 但我没有找到任何答案。
我有一个启动一个线程主线程(我的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;
}