我正在尝试实现一个可以处理多个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
}发布于 2013-03-26 10:25:04
如果您这样做:
pthread_create( &id , NULL , worker , (void*) epoll_fd + i);在线程函数中,这是:
void *worker(void *vp_epfd) {
int *p_epfd = (int*) vp_epfd;那么它应该是工作的,并且是线程安全的,假设您在正确的位置检查了*p_epfd中的更新。
https://stackoverflow.com/questions/15626234
复制相似问题