2013-04-02 74 views
0

我已经辑阵线程与工作线程的应用程序,我使用哈希表路由消息之间有两个运行结束SD(插座descriptores),每个线程时,epoll_wait等待新的连接,因此当新sd被创建,它将被添加到哈希中,并且它将开始路由信息。没有互斥锁可以从散列中删除吗?或者下面的假设是正确的?的epoll和哈希表

我在想它的原因是因为我将从哈希中删除,它应该是安全的,因为除非用close(sd)关闭,否则新的sd#将不会具有保存在哈希中的相同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

你的代码示例并不是那么清楚。线程如何相互关联?像epoll_wait()这样的地方没有显示正常的参数。大多数情况下,单个线程将调用epoll_wait()来为多个fd服务。但是,如果你有多个线程执行自己的epoll_wait(),然后再引用一个哈希表,最有可能的是哈希需要MT保护。