我有带有工作线程的多线程应用程序,我使用哈希表在两个打开的 sd(套接字描述符)之间路由消息,每个线程都在等待 epoll_wait 等待新连接,因此当创建新的 sd 时,它将被创建添加到哈希中,它将开始路由消息。可以在没有互斥锁的情况下从哈希中删除吗?或者下面的假设是否正确?
我之所以考虑它,是因为我将从哈希中删除它,并且它应该是安全的,因为新的 sd # 不会在哈希中保存相同的 sd #,除非它用 close(sd) 关闭。
//Global var
struct route_table {
int from_sd;
int to_sd;
};
//end of global var
int main()
{
route_table = malloc(sizeof(struct route_table) * file-max); //allocate an array for all fds from /proc/sys/fs/file-max
}
void *worker_function(void *)//lpthread
{
epoll_wait()
if (events & EPOLLIN)
{
if (route_table[fd].from_sd == fd)
send_msg(route_table[fd].to_sd, msg)
}
if (events & EPOLLERR)
//EPOLLERR above is just an example, I'm covering all other errors
{
if (route_table[fd].from_sd == fd) {
route_table[fd].to_sd = 0; //remove from hash
route_table[fd].from_sd = 0; //remove from hash then another worker thread starts working, so the other worker won't hit the same slot as the sd is still open for this thread
shutdown(sd, SHUT_RDWR);//we don't care about this one
close(sd); //now control is back for this thread then this sd will be removed and now new thread can have the same sd # with no problem
}
}
}
最佳答案
您的代码示例不太清楚。线程之间如何关联?像 epoll_wait() 这样的地方没有显示正常的参数。最典型的是,单个线程将调用 epoll_wait() 来服务多个 fd。但是,如果您有多个线程执行自己的 epoll_wait(),然后引用回哈希表,则该哈希很可能需要 MT 保护。
关于c - 线程中的 epoll 和哈希表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15754582/