c - 线程 worker 和 epoll

标签 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
}

最佳答案

如果你这样做:

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

在线程函数中,这个:

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

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

关于c - 线程 worker 和 epoll,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15626234/

相关文章:

c - 如果用户没有在 C 中引入 3 位数字,则打印错误

c - 如果使用函数 i 返回一个在其中创建的指针,函数结束后指针在函数中创建的 4 个字节是否会被释放?

linux - 当 nginx 给出 502 bad gateway 时如何调试?

linux - 学习linux开发用什么版本?

java - Kryonet RMI,无法等待连接更新线程的响应

c++ - 处理多端口服务器

c - 被 pthread_cond_signal() 唤醒但失去对互斥锁竞争的线程会发生什么

c - 让 : *** No targets specified and no makefile found. 停止。在 Xcode 上

mysql - 如何找到 MySQL 守护程序错误日志的位置?

sockets - 网络编程中流和数据报有什么区别?