c - 线程中的 epoll 和哈希表

标签 c linux multithreading epoll

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

相关文章:

C/CAPL 从另一个数组定义一个数组

c - 如何检查多个变量是否包含简单序列

c - 在 AT&T IA-32 Linux 汇编程序 (gas) 上拆分字符串

linux - 检查 SSH 隧道是否已启动并正在运行

linux - 当文件名的一部分时,Shell 脚本不执行星号

java - 在 Java 中,当我们从正在执行 Future 线程的函数返回时会发生什么?

c - 在c中实现pacman,幽灵运动

c - C语言有没有不用等待输入就可以检查用户是否输入的命令

c# - 修改集合时将线程从 sleep 中唤醒

java - ConcurrentHashMap中,如何同步更新?