muduo源码分析之EventLoop::runInLoop()函数

本文深入探讨了muduo库中EventLoop::runInLoop()函数的实现,讲解了如何利用eventfd唤醒线程以及在EventLoop中执行用户回调。文中通过示例详细阐述了线程间通信和EventLoop对象在多线程环境中的使用,包括EventLoopThread的工作原理。
摘要由CSDN通过智能技术生成

前面所学的一些内容,从最早的什么都不做的EventLoop开始,到后面的定时器,功能不断在丰富,不过一直都是单线程下的。也就是说EventLoop对象在主线程中进行事件循环。今天花了一天时间所学习的EventLoop::runInLoop()就打开muduo多线程编程的大门。

1.eventfd唤醒线程

先来看看这个eventfd的用法,直接上示例:

#include <stdio.h>  
#include <unistd.h>  
#include <sys/time.h>  
#include <stdint.h>  
#include <pthread.h>  
#include <sys/eventfd.h>  
#include <sys/epoll.h>  

int efd = -1;  

void *read_thread(void *dummy)  
{  
    int ret = 0;  
    uint64_t count = 0;  
    int ep_fd = -1;  
    struct epoll_event events[10];  

    if (efd < 0)  
    {  
        printf("efd not inited.\n");  
        goto fail;  
    }  

    ep_fd = epoll_create(1024);  
    if (ep_fd < 0)  
    {  
        perror("epoll_create fail: ");  
        goto fail;  
    }  

    {  
        struct epoll_event read_event;  

        read_event.events = EPOLLHUP | EPOLLERR | EPOLLIN;  
        read_event.data.fd = efd;  

        ret = epoll_ctl(ep_fd, EPOLL_CTL_ADD, efd, &read_event);  
        if (ret < 0)  
        {  
            perror("epoll ctl failed:");  
            goto fail;  
        }  
    }  

    while (1)  
    {  
        ret = epoll_wait(ep_fd, &events[0], 10, 5000);  
        if (ret > 0)  
        {  
            int i = 0;  
            for (; i < ret; i++)  
            {  
                if (events[i].events & EPOLLHUP)  
              
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值