我有带有工作线程的多线程应用程序,我正在使用哈希表在两个 opend 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
}
}
}