eventfd和epoll的結合使用

eventfd其實是內核為應用程序提供的異步信號量,在內核中以文件存在
eventfd -創(chuàng)建事件通知的文件描述符。
eventfd()創(chuàng)建了一個“eventfd對象”,可以作為用戶空間應用程序的事件等待/通知機制,內核以通知用戶空間應用程序的事件。該對象包含一個未簽署的64位整數(shù)(uint64_t)計數(shù)器.這是由內核維護的。
這個計數(shù)器是用參數(shù)initval中指定的值初始化的。

include < sys / eventfd.h >
int eventfd(unsigned int initval,int flags);

eventfd在內核里的核心是一個計數(shù)器counter,它是一個uint64_t的整形變量counter,初始值為initval。
既然是文件,那么我們就可以執(zhí)行read 和write 操作

Read:

消費者需要對信號量進行down操作時,調用read從eventfd讀即可。
read返回值:
如果當前counter > 0,read返回counter值,并重置counter為0;
如果當前counter等于0,1>阻塞直到counter大于0;2>如果設置了NONBLOCK,那么返回-1,并設置errno為EAGAIN。
可以看到,eventfd實現(xiàn)的資源是一次性消耗品,只允許一次read。

Write

當需要執(zhí)行up操作時,調用write寫一個64bit的整數(shù)value到eventfd即可。write返回值:
counter最大能存儲的值是 0xffff ffff ffff fffe(以max表示此值),那么write嘗試將value加到counter上,如果結果超過max,那么write一直阻塞直到有read操作發(fā)生,或者返回-1并設置errno為EAGAIN。

epoll,談起epoll,總避免不了說起select,兩者都是一種linux異步執(zhí)行的方式,舉個例子,如果你宿舍在302,你告訴宿舍管理員如果等會有你的快遞就到302通知你一聲,當快遞來的時候,宿舍管理員直接到302告訴你:嘿,同學你的快遞到了,這就是Epoll;管理員要是挨個挨個房間問:這個快遞是不是你的?直到找到為止,這就是Select.
epoll的接口非常簡單,一共就三個函數(shù):

// 創(chuàng)建一個epoll的句柄
1、 int epfd = epoll_create(intsize);  
// epoll的事件注冊函數(shù),監(jiān)聽事件類型
2、int epoll_ctl(int epfd, intop, int fd, struct epoll_event*event); 
//等待事件觸發(fā),當超過timeout還沒有事件觸發(fā)時,就超時
3、int epoll_wait(int epfd, struct epoll_event * events, intmaxevents, int timeout);

下面這一段代碼希望能幫助大家理解:

#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)
    {
      //epoll_wait會引起阻塞,直到2s超時時間過去或者在2S內有數(shù)據(jù)寫入efd
        ret = epoll_wait(ep_fd, &events[0], 10, 2000);
        if (ret > 0)
        {
            int i = 0;
            for (; i < ret; i++)
            {
                if (events[i].events & EPOLLHUP)
                {
                    printf("epoll eventfd has epoll hup.\n");
                    goto fail;
                }
                else if (events[i].events & EPOLLERR)
                {
                    printf("epoll eventfd has epoll error.\n");
                    goto fail;
                }
                else if (events[i].events & EPOLLIN)
                {
                    int event_fd = events[i].data.fd;
                    ret = read(event_fd, &count, sizeof(count));
                    if (ret < 0)
                    {
                        perror("read fail:");
                        goto fail;
                    }
                    else
                    {
                        struct timeval tv;

                        gettimeofday(&tv, NULL);
                        printf("success read from efd, read %d bytes(%llu) at %lds %ldus\n",
                               ret, count, tv.tv_sec, tv.tv_usec);
                    }
                }
            }
        }
        else if (ret == 0)
        {
            /* time out */
            printf("epoll wait timed out.\n");
            break;
        }
        else
        {
            perror("epoll wait error:");
            goto fail;
        }
    }

fail:
    if (ep_fd >= 0)
    {
        close(ep_fd);
        ep_fd = -1;
    }

    return NULL;
}


int main(int argc, char *argv[])
{
    pthread_t pid = 0;
    uint64_t count = 0;
    int ret = 0;
    int i = 0;
    efd = eventfd(0, 0);
    if (efd < 0)
    {
        perror("eventfd failed.");
        goto fail;
    }
    ret = pthread_create(&pid, NULL, read_thread, NULL);
    if (ret < 0)
    {
        perror("pthread create:");
        goto fail;
    }
    for (i = 0; i < 5; i++)
    {
        count = 4;
        ret = write(efd, &count, sizeof(count));
        if (ret < 0)
        {
            perror("write event fd fail:");
            goto fail;
        }
        else
        {
            struct timeval tv;

            gettimeofday(&tv, NULL);
        printf("success write to efd, write %d bytes(%llu) at %lds %ldus\n",
                   ret, count, tv.tv_sec, tv.tv_usec);
        }

        sleep(10);
    }

fail:
    if (0 != pid)
    {
        pthread_join(pid, NULL);
        pid = 0;
    }

    if (efd >= 0)
    {
        close(efd);
        efd = -1;
    }
    return ret;
}


?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容