2013-04-02 29 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保護。