我有使用工作线程的mutli线程应用程序,我使用哈希表在两个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
}
}
}
答案 0 :(得分:0)
您的代码示例并不是那么清楚。线程如何相互关联?像epoll_wait()这样的地方没有显示正常的参数。最典型的是,单个线程将调用epoll_wait()来为多个fd提供服务。但是,如果您有多个线程在执行自己的epoll_wait()然后再引用哈希表,则很可能哈希需要MT保护。