기본 콘텐츠로 건너뛰기

새로운 노트북

epoll은 공평한가?

epoll은 공평할까?
$man epoll...
o Starvation ( Edge Triggered ): If there is a large amount of I/O space, it is possible that by trying to drain it the other files will not get processed causing starvation. This is not specific to epoll. The solution is to maintain a ready list and mark the file descriptor as ready in its associated data structure, thereby allowing the application to remember which files need to be processed but still round robin amongst all the ready files. This also supports ignoring subsequent events you receive for fd's that are already ready....
Edge Triggered에서 기아상태. 특별히 epoll에 국한된 문제는 아니라고 하는군. ㅡ_-)a 기본값은 Level Triggered이지만 정리하는 차원에서.
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <iostream>
#include <vector>
#include <errno.h>
#include <pthread.h>
#include <sys/time.h>
#include <signal.h>
using namespace std;

static
long long
getTimestamp(void)
{
    static struct timeval tv;
    gettimeofday(&tv,NULL);
    return 1000000LL*tv.tv_sec+tv.tv_usec;
}

static const size_t g_socket_count(200/2);
static const size_t g_count_per_poll(5);
static const long long g_timeout(1000*1000);
static const size_t g_test_count(10000);
static pid_t g_child_pid(0);

class pairsock
{
public:
    pairsock() : m_last(getTimestamp()), m_stat(0)
    {
    }

public:
    operator int* (void)
    {
        return m_socks;
    }

    operator const int* (void) const
    {
        return m_socks;
    }

    const int& operator [] ( size_t idx ) const
    {
        return m_socks[idx];
    }

    int& operator [] ( size_t idx )
    {
        return m_socks[idx];
    }

    bool create(void)
    {
        return -1 != socketpair(AF_UNIX,
            SOCK_STREAM, AF_LOCAL, m_socks);
    }

    void destroy(void)
    {
        close(m_socks[0]);
        close(m_socks[1]);
    }

    long long last(void) const
    {
        return m_last;
    }

    void last(long long lo)
    {
        m_last= lo;
    }

    void increase(void)
    {
        ++m_stat;
    }

    size_t stat(void) const
    {
        m_stat;
    }

    void stat(size_t s)
    {
        m_stat = s;
    }

protected:
    int m_socks[2];
    long long m_last;
    size_t m_stat;
};

typedef vector<pairsock*> sock_cont;

static sock_cont g_sockets;
static int g_epoll_handle;

void*
_Thread(void* param)
{
    sock_cont::const_iterator ib, ie;
    static const size_t idx(*(size_t*)param);
    char c(0x00);

    do
    {
        ib = g_sockets.begin();
        ie = g_sockets.end();
        while ( ib != ie )
        {
            write((**ib)[idx], &c, sizeof(c));
            ++ib;
        }

        ++c;
    } while (true);
    pthread_exit(NULL);
}

bool
initSocks(size_t size)
{
    pairsock* ps(NULL);

    for ( size_t i(0); i<size; i++ )
    {
        ps = new pairsock;
        if ( !ps )
        {
            return false;
        }

        if ( !ps->create() )
        {
            cerr << "index: " << i << endl;
            delete ps;
            return false;
        }

        g_sockets.push_back(ps);
    }

    return true;
}

bool
initEpoll(bool bParent)
{
    g_epoll_handle = epoll_create(g_socket_count);
    if ( -1 == g_epoll_handle ) return false;

    static struct epoll_event ev;
    ev.events = EPOLLIN;

    for (size_t i(0); i<g_socket_count; i++)
    {
        ev.data.ptr = g_sockets[i];
        if ( -1 == epoll_ctl(g_epoll_handle, EPOLL_CTL_ADD,
            g_sockets[i]->operator[](0),
            &ev) )
        {
            cerr << i << endl;
            cerr << getpid() << "epoll_ctl("
                << g_sockets[i]->operator[](0)
                 << ')' << endl;
            return false;
        }
    }

    return true;
}

void
find_starvation(void)
{
    static long long now(getTimestamp());
    static sock_cont::const_iterator ib, ie;
    ib = g_sockets.begin();
    ie = g_sockets.end();

    while ( ib != ie )
    {
        if ( now - (*ib)->last() > g_timeout )
        {
            cerr << "timeout: " << (*ib)->operator [] (0) << endl;
        }

        ++ib;
    }
}

void
main_loop(bool bTrace)
{
    static struct epoll_event* evs;
    evs = new struct epoll_event [g_count_per_poll];
    static struct epoll_event* ep;
    int res, i;
    char c;
    pairsock* ps(NULL);
    size_t cnt(0);

    do
    {
        res = epoll_wait(g_epoll_handle, evs, g_count_per_poll, 1000);
        if ( bTrace )
        {
            cerr << cnt << ':';
        }

        for ( i = 0, ep = evs; i < res; i++, ep++ )
        {
            ps = (pairsock*)ep->data.ptr;
            read(ps->operator [] (1), &c, sizeof(c));
            ps->last(getTimestamp());
            ps->increase();
            if ( bTrace )
            {
                cerr << ps->operator [] (1) << ", ";
            }
        }

        if ( bTrace )
        {
            cerr << endl;
        }

        find_starvation();
        ++cnt;
    } while (cnt < g_test_count || !bTrace);

    if ( !bTrace )
    {
        return;
    }

    cerr << "=================================" << endl;
    sock_cont::const_iterator ib(g_sockets.begin());
    sock_cont::const_iterator ie(g_sockets.end());

    while ( ib != ie )
    {
        cerr << (*ib)->operator [] (0) << ':' << (*ib)->stat() << '/'
            << (*ib)->last() << endl;
        ++ib;
    }

    kill(g_child_pid, SIGKILL);
}

int
main(int,char**)
{
    do
    {
        if ( !initSocks(g_socket_count) ) break;

        g_child_pid = fork();
        const bool bParent(g_child_pid?true:false);
        size_t write_idx(bParent?1:0);

        pthread_t handle_thread;
        pthread_create(&handle_thread, NULL, _Thread, &write_idx);
        pthread_detach(handle_thread);

        if ( !initEpoll(bParent) ) break;

        main_loop(bParent);
    } while (false);

    cerr << strerror(errno) << endl;
    return errno;
}


ㅡ_-) 뭐, 이런 종류 테스트가 그렇겠지만, 소스가 좀 기네. 여기서 하고자 하는 테스트는 부모자식이 pair socket을 n개(정확히는 n*2개)를 가지고 각각 n[1]에 write를 하고, n[0]에서 read를 하도록 하였다. write는 쓰레드가 담당하며, read는 main_loop가 담당한다. 참고로 ET가 아니라 LT이다. ET를 쓸만한 껀덕지가 그닥.

  • g_socket_count -총 pair socket 개수이다. n/2 형태로 해서 표현해놨다.
  • g_count_per_poll - epoll_wait로부터 한 번에 읽어오는 이벤트 개수이다.
  • g_timeout - 기아를 판단하기 위한 timeout. 단위는 마이크로(1/10^6)초이다.
  • g_test_count - epoll_wait 호출 회수. 걍 놔두자.

여기서 g_socket_count가 상당히 크고, g_count_per_poll이 상당히 작을 때, 기아가 발생할까? 위와 같이 100개를 감시하고, 그 중에 5개씩 뽑아오는 것을 돌려보았다.

결과는 기아는 발생하지 않았으며, 상당히 고르게 이벤트를 뜨는 것을 알 수 있었다. (후훗!)

댓글

이 블로그의 인기 게시물

Bash Array, Map 정리

Bash에서 Array, Map에 대한 정리. (매번 찾기 귀찮) 찾아보진 않았지만, Bash에서 Array든 Map이든 동일하게 Map(C++에서 Unordered Map)으로 동작하는 것 같다. 왜냐하면, Array의 Index가 연속하지 않아도 동작한다. 그저 Key가 0 이상의 정수인 Map이랑 비슷하게 동작한다. 예) 1, 2, 3, 9, 10 Array # 생성 declare -a empty_array declare -a ar=(haha hoho baba "long string haha hoho") # 접근 echo "ar[0]=${ar[0]}" echo "all as array=${ar[@]}" # 큰따옴표 안에서 각 원소를 따로따로 전달한다. echo "all as one=${ar[*]}" # 큰따옴표 안에서 각 원소를 문자열 하나로 합쳐 전달한다. echo "indexes=${!ar[@]}" echo "indexes=${!ar[*]}" echo "length=${#ar[@]}" echo "length=${#ar[*]}" echo "last=${ar[-1]}" echo "last=${ar[@]: -1}" # 콜론 뒤에 빈 칸이 꼭 필요하다. 옛 방식 # 현재 상황 declare -p ar #(출력) declare -a ar=([0]="haha" [1]="hoho" [2]="baba" [3]="long string haha hoho") ar[100]=hello # 인덱스를 건너 뛰어도 동작한다. declare -p ar #(출력) declare -a ar=([0]="haha" [1]="hoho" [2]="baba" [3]=&

설치한 패키지에서 RPM 추출하기

오래된 패키지를 관리할 저장소가 없어졌고, 기존 패키지로 다른 서버를 세팅해야할 일이 생겼다면 RPM의 리패키지 기능을 이용해보자. $ rpm -e --repackage [PACKAGE_NAME] 위와 같이 리패키지하면, /var/spool/repackage/ 에 생성한 RPM파일이 있다. :-)