前面所学的一些内容,从最早的什么都不做的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)