新版本的glib支持使用外部的事件循环代替内部的poll,这篇文章使用的glib版本是V2.72.0, 理解还很粗浅,但是demo能跑起来,还需要再详细研究一下参考的两个链接,多线程下使用及效率是怎样的都还不清楚。
1、新API
通过新的API g_main_context_new_with_flags 及新变量G_MAIN_CONTEXT_FLAGS_OWNERLESS_POLLING可以创建一个无主的poll,然后通过glib的一套API可以实现自己的事件循环。ubuntu18下的demo:
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <glib.h>
#include <sys/epoll.h>
static GMainContext *watchdog_context = NULL;
int num = 0;
static gboolean cb_check(gpointer user_data)
{
printf("In cb_check %d \n", num);
}
char* name = "ori";
static gpointer cb_watchdog(gpointer user_data)
{
num = 1;
GMainLoop *loop = (GMainLoop *) user_data;
GMainContext *watchdog_context = g_main_loop_get_context(loop);
GSource *timeout_source;
timeout_source = g_timeout_source_new_seconds(2);

本文介绍了如何在Glib V2.72.0版本中利用新API创建无主poll,并结合epoll实现自定义事件循环。通过示例代码展示了如何在多线程环境下启动事件监听和处理,同时探讨了glib_event_2_epoll和epoll_event_2_glib转换函数的使用。虽然目前对新特性的理解尚浅,但已成功运行了示例程序,后续将进一步研究其在多线程和效率方面的表现。
最低0.47元/天 解锁文章

1830

被折叠的 条评论
为什么被折叠?



