我正在尝试实现一个处理许多 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/