2015-12-09 19 views
1

我正在編寫一個程序,其中多個線程將條目添加到(tbb :: concurrent_hash_map)哈希映射中,同時其他線程遍歷該映射並操作哈希映射上的條目。在每次一個線程操縱並使用一個入口並使用訪問者阻止該入口(以便不會有衝突並且其他線程無法訪問該入口)。操作數據後,線程插入數據並釋放訪問器。tbb :: concurrent_hash_map - 如果鍵入被其他線程阻塞,如何返回

我現在的問題是,一個線程如何訪問被阻止的條目,直到該條目的訪問者被釋放,即使哈希映射中的其他條目未被阻止。我想要實現的目標是,線程跳過被阻止的條目並轉到下一個非阻止條目或返回到我的函數。有沒有很好的解決方案?

下面的代碼片段短單線程例如:

... 
typdef tbb::concurrent_hash_map<int,unsigned int> typ_hash_map; 
typ_hash_map hash_map; 
typ_hash_map::accessor acc; 
typ_hash_map::accessor acc2; 
//hash_map filled with 4 entries... 

//block second entry in hash map 
typ_hash_map::iterator k = hash_map.begin(); 
k++; 
config.hash_map.insert(acc,k->first); 

//travers all entries in hash_map 
for(typ_hash_map::iterator j = hash_map.begin();j!=hash_map.end(); j++){ 
      hash_map.find(acc2,j->first); // my problem: return if entry is blocked - at the moment its waiting till acc is released 
      /* 
      Do something with acc2->second if entry is not blocked, 
      else continue; 
      */ 
      } 
... 

回答

0

你知道穿越tbb::concurrent_hash_map不是線程安全的嗎?如果你的代碼是串行的,那麼就沒有什麼可以保護的:所以,你不需要保存一個訪問器。

無論如何,長時間鎖定一個元素是一個壞主意,因爲它會傷害可擴展性並導致類似你的死鎖,所以當更新完成或讀取數據時應立即釋放。

concurrent_hash_map的一般規則是:不要在其他acccessors上執行任何哈希表操作,同時保留第一個哈希表。

所以,只要你完成它就立即發佈訪問者accacc.release()