线程工作者和epoll

时间:2013-03-25 22:45:01

标签: c linux network-programming

我正在尝试实现一个处理许多tcp连接的服务器,每天100到1000个连接,基于一天中的时间。在阅读了大量关于每个连接的线程的c10k问题并且仅使用epoll之后,我决定将两者用作线程池,并且main将充当调度程序,因此每个新连接将被分配给线程。

我有很多问题在其他任何地方找不到答案。 以下线程安全吗?在添加新的fd之前我需要锁定吗?

int main ()
{
    while(i < number_threads)
      {         
        pthread_create( &id , NULL ,  worker , (void*) epoll_fd[i]);
        i++;
      }


//is it ok to add the new_sock for the epoll_fd[i] so the thread can pick it up
int y = 0;
    while(1) {
        new_sock = accept(...);
           if (epoll_ctl(epoll_fd[y], EPOLL_CTL_ADD, new_sock, &ev) < 0)
            {
                print error; 
            }
    y++;
    if (y == number_threads)
    y = 0;
    }

}



void *worker(void *epfd)
{
epoll_wait //start waiting for event
}

1 个答案:

答案 0 :(得分:0)

如果你这样做:

pthread_create( &id , NULL ,  worker , (void*) epoll_fd + i);

并在线程函数中,这个:

void *worker(void *vp_epfd) {
  int *p_epfd = (int*) vp_epfd;

然后它应该可以工作,并且是线程安全的,假设您在*p_epfd中检查更正的位置。