關于linux中select和epoll是否存在驚群效應的爭執

親測,先給出結論:
select不存在驚群效應,每次來一個socket消息,只有一個消費進程被喚醒。
e_poll存在驚群效應,每次來一個socket連接請求,處于空閑狀態的消費進程都被喚醒。

先對select機制的測試,直接上代碼:

//select測試
#include <sys/types.h>  
#include <sys/socket.h>  
#include <netinet/in.h>  
#include <sys/wait.h>  
#include <stdio.h>  
#include <string.h>  
#define PROCESS_NUM 10  
int main()  
{  
    int fd = socket(PF_INET, SOCK_STREAM, 0);  
    int connfd;  
    int pid;  
    char sendbuff[1024];  
    struct sockaddr_in serveraddr;  
    serveraddr.sin_family = AF_INET;  
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);  
    serveraddr.sin_port = htons(1234);  
    bind(fd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));  
    listen(fd, 1024);  
    int i;  
    for(i = 0; i < PROCESS_NUM; i++)  
    {  
        int pid = fork();  
        if(pid == 0)  
        {  
            while(1)  
            {  
                connfd = accept(fd, (struct sockaddr*)NULL, NULL);  
                snprintf(sendbuff, sizeof(sendbuff), "accept PID is %d\n", getpid());  
                
                send(connfd, sendbuff, strlen(sendbuff) + 1, 0);  
                printf("process %d accept success!\n", getpid());  
                close(connfd);  
            }  
        }  
    }  
    int status;  
    wait(&status);  
    return 0;  
} 

測試結果,服務端為:

[root@localhost operea_study]# gcc select.c -o a
[root@localhost operea_study]# ./a
process 12515 accept success!

客戶端為:

[minping@localhost ~]$ curl 127.0.0.1:1234
accept PID is 12515
[minping@localhost ~]$ 

證明linux的select不存在驚群效應:當多個進程都阻塞在對同一個socket的accept上,當有一個新的連接到來時,,確實只有一個進程被內核喚醒,其他進程還是繼續保持休眠狀態。

然后對e_poll的測試:

#include <sys/types.h>  
#include <sys/socket.h>  
#include <sys/epoll.h>  
#include <netdb.h>  
#include <string.h>  
#include <stdio.h>  
#include <unistd.h>  
#include <fcntl.h>  
#include <stdlib.h>  
#include <errno.h>  
#include <sys/wait.h>  
#define PROCESS_NUM 10  
static int  
create_and_bind (char *port)  
{  
    int fd = socket(PF_INET, SOCK_STREAM, 0);  
    struct sockaddr_in serveraddr;  
    serveraddr.sin_family = AF_INET;  
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);  
    serveraddr.sin_port = htons(atoi(port));  
    bind(fd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));  
    return fd;  
}  
    static int  
make_socket_non_blocking (int sfd)  
{  
    int flags, s;  
 
    flags = fcntl (sfd, F_GETFL, 0);  
    if (flags == -1)  
    {  
        perror ("fcntl");  
        return -1;  
    }  
 
    flags |= O_NONBLOCK;  
    s = fcntl (sfd, F_SETFL, flags);  
    if (s == -1)  
    {  
        perror ("fcntl");  
        return -1;  
    }  
 
    return 0;  
}  
  
#define MAXEVENTS 64  
 
int  
main (int argc, char *argv[])  
{  
    int sfd, s;  
    int efd;  
    struct epoll_event event;  
    struct epoll_event *events;  
 
    sfd = create_and_bind("1234");  
    if (sfd == -1)  
        abort ();  
 
    s = make_socket_non_blocking (sfd);  
    if (s == -1)  
        abort ();  
 
    s = listen(sfd, SOMAXCONN);  
    if (s == -1)  
    {  
        perror ("listen");  
        abort ();  
    }  
 
    efd = epoll_create(MAXEVENTS);  
    if (efd == -1)  
    {  
        perror("epoll_create");  
        abort();  
    }  
 
    event.data.fd = sfd;  
    //event.events = EPOLLIN | EPOLLET;  
    event.events = EPOLLIN;  
    s = epoll_ctl(efd, EPOLL_CTL_ADD, sfd, &event);  
    if (s == -1)  
    {  
        perror("epoll_ctl");  
        abort();  
    }  
 
    /* Buffer where events are returned */  
    events = calloc(MAXEVENTS, sizeof event);  
            int k;  
    for(k = 0; k < PROCESS_NUM; k++)  
    {  
        int pid = fork();  
        if(pid == 0)  
        {  
 
            /* The event loop */  
            while (1)  
            {  
                int n, i;  
                n = epoll_wait(efd, events, MAXEVENTS, -1);  
                printf("process %d return from epoll_wait!\n", getpid());  
                                       /* sleep here is very important!*/  
                //sleep(2);  
                                       for (i = 0; i < n; i++)  
                {  
                    if ((events[i].events & EPOLLERR) || (events[i].events & EPOLLHUP) || (!(events[i].events &                                    EPOLLIN)))  
                    {  
                        /* An error has occured on this fd, or the socket is not  
                        ready for reading (why were we notified then?) */  
                        fprintf (stderr, "epoll error\n");  
                        close (events[i].data.fd);  
                        continue;  
                    }  
                    else if (sfd == events[i].data.fd)  
                    {  
                        /* We have a notification on the listening socket, which  
                        means one or more incoming connections. */  
                        struct sockaddr in_addr;  
                        socklen_t in_len;  
                        int infd;  
                        char hbuf[NI_MAXHOST], sbuf[NI_MAXSERV];  
 
                        in_len = sizeof in_addr;  
                        infd = accept(sfd, &in_addr, &in_len);  
                        if (infd == -1)  
                        {  
                            printf("process %d accept failed!\n", getpid());  
                            break;  
                        }  
                        printf("process %d accept successed!\n", getpid());  
 
                        /* Make the incoming socket non-blocking and add it to the  
                        list of fds to monitor. */  
                        close(infd); 
                    }  
                }  
            }  
        }  
    }  
    int status;  
    wait(&status);  
    free (events);  
    close (sfd);  
    return EXIT_SUCCESS;  
}  

服務端測試結果:

[root@localhost operea_study]# gcc e_poll.c -o b
[root@localhost operea_study]# ./b
process 12778 return from epoll_wait!
process 12779 return from epoll_wait!
process 12779 accept successed!
process 12780 return from epoll_wait!
process 12787 return from epoll_wait!
process 12781 return from epoll_wait!
process 12786 return from epoll_wait!
process 12786 accept failed!
process 12780 accept failed!
process 12785 return from epoll_wait!
process 12782 return from epoll_wait!
process 12783 return from epoll_wait!
process 12784 return from epoll_wait!
process 12784 accept failed!
process 12778 accept failed!
process 12781 accept failed!
process 12787 accept failed!
process 12783 accept failed!
process 12782 accept failed!
process 12785 accept failed!

客戶端測試結果:

[minping@localhost ~]$ curl 127.0.0.1:1234
curl: (52) Empty reply from server
[minping@localhost ~]$ 

發現epoll下,10個監聽在這個socket上處于epoll_wait狀態的進程,在有連接請求過來的時候,都被喚醒了,驚群效應發生。
再過一下事件的經過:當主進程創建socket,然后bind,然后listen后,將該socket加入到epoll中。然后fork出多個進程,每個進程都阻塞在對這個socket監聽的epoll_wait上,當有一個新的連接過來時,發現這些進程全部被喚醒。

那么問題來了,為什么linux內核對select做了修復,避免了驚群效應的發生,而對epoll卻不進行處理,到目前為止,epoll還是會發生驚群效應呢?

下面摘抄自網友的一段話,覺得說的還比較在理:

accept確實應該只能被一個進程調用成功,但是epoll的情況就比較復雜,epoll監聽的文件描述符,
除了可能后續被accept調用外,還可能是其他網絡IO事件的監聽對象,那其他網絡IO是否只能由一個進程處理我們是不得知的。
所以linux對epoll并沒有就驚群效應做修復,而是放之,讓用戶層自己做處理。

第二個問題,上面說了linux對epoll并沒有修復驚群效應問題,而是留給用戶層(業務層)自己來處理,那么nginx是怎么處理驚群效應的呢?

nginx的網絡架構大致是這樣的:讀取主配置文件創建socket,bind,listen等一系列動作做好后,fork出一堆子進程(為了最大限度利用cpu,一般幾個核就fork幾個子進程),然后每個子進程會調用ngx_event_process_init 函數來初始化自己進程的內部的連接池。ngx_event_process_init 函數還有一個很重要的工作就是:如果如果配置文件里面沒有開啟accept_mutex鎖的話,就通過 ngx_add_event 將監聽套接字(socket fd)添加到每個fork出來的子進程的 epoll 中。

每個子進程的ngx_event_process_init 函數執行完后就會在一個死循環中執行ngx_process_events_and_timers,這個函數會讀取配置文件里面有沒有開啟accept mutex鎖,如果開啟了accept mutex鎖,則此進程會嘗試獲取鎖,獲取成功就將socket fd當道自己這個子進程的epoll中。ngx_process_events_and_timers再調用 ngx_process_events,在 ngx_process_events這個函數里面阻塞調用 epoll_wait。

總結來說,nginx就是利用 accept_mutex 這把鎖來解決epoll_wait驚群問題的。

如果配置文件中沒有開啟 accept_mutex,則所有的監聽套接字不管三七二十一,都加入到每子個進程的 epoll中,這樣當一個新的連接來到時,所有的 worker 子進程都會驚醒。

如果配置文件中開啟了 accept_mutex,則只有一個子進程會將監聽套接字添加到 epoll 中,這樣當一個新的連接來到時,當然就只有一個 worker 子進程會被喚醒了。

總結:
1,accept 不會有驚群,epoll_wait 才會。
2,Nginx 的 accept_mutex,并不是解決 accept 驚群問題,而是解決 epoll_wait 驚群問題。
3,說Nginx 解決了 epoll_wait 驚群問題,也是不對的,它只是控制是否將監聽套接字加入到子進程的epoll 中。監聽套接字只在一個子進程的 epoll 中,當新的連接來到時,其他子進程當然不會驚醒了。

參考

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 第一章 Nginx簡介 Nginx是什么 沒有聽過Nginx?那么一定聽過它的“同行”Apache吧!Ngi...
    JokerW閱讀 32,795評論 24 1,002
  • 本文系轉載》》》》》》》》》》》》》》》》 編者按:高可用架構分享及傳播在架構領域具有典型意義的文章,本文由陳科在...
    demop閱讀 8,117評論 0 7
  • 什么是Nginx? Nginx是一個高性能的HTTP和反向代理服務器,也是一個IMAP/POP3/SMTP服務器N...
    jiangmo閱讀 2,585評論 1 9
  • 上一篇《WEB請求處理一:瀏覽器請求發起處理》,我們講述了瀏覽器端請求發起過程,通過DNS域名解析服務器IP,并建...
    七寸知架構閱讀 81,227評論 21 356
  • 小時候,我總想著如何逃離故鄉。是啊,我覺得這里的人太粗俗,這個地方太窮,這個的爸爸媽媽一點也不愛我。 后來,我真的...
    淺輒止閱讀 575評論 0 2