我正在爲我的項目(Linux,ICC,pthreads)優化一些儀器,並希望對此技術提供一些反饋,爲一個線程分配一個唯一的索引,這樣我就可以使用它來索引每個線程的數組數據。我可以使用pthreads分配每個線程的索引嗎?
舊的技術使用基於pthread id的std :: map,但我想避免鎖定和地圖查找(如果可能的話)(它會產生大量的開銷)。
這是我的新技術:
static PerThreadInfo info[MAX_THREADS]; // shared, each index is per thread
// Allow each thread a unique sequential index, used for indexing into per
// thread data.
1:static size_t GetThreadIndex()
2:{
3: static size_t threadCount = 0;
4: __thread static size_t myThreadIndex = threadCount++;
5: return myThreadIndex;
6:}
在後面的代碼:
// add some info per thread, so it can be aggregated globally
info[ GetThreadIndex() ] = MyNewInfo();
所以:
1)它看起來像4號線可能是,如果兩個線程的競爭條件在同一時間創建。如果是這樣 - 我怎樣才能避免這種情況(最好沒有鎖)?我看不出原子增量會在這裏起到什麼作用。
2)有沒有更好的方法來創建每線程索引莫名其妙?也許通過以某種方式預先生成線程創建的TLS索引?
1)當然,謝謝你清理那個。 2)這是真的 - 但不幸的是我想要從任何線程「讀取」信息,定期進行聚合。 – Justicle 2011-04-02 23:12:46