我正在为我的项目(Linux、ICC、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 索引?