【发布时间】:2019-01-08 07:59:08
【问题描述】:
我想给每个进入函数的线程一个对象,它只会使用它(在这种情况下,它代表一页内存)。这是为了帮助减少我的程序遇到瓶颈的同步,因此理想情况下它本身不需要锁定互斥锁。
我正在尝试做的极简主义示例(std::map 不能同时插入,但如果可以,这将完全满足我的需要):
// multiple threads can access this, they should be able to do so without synchronization
void addJob(ThreadMemory * mem){
// straight-forward, but undefined when used concurrently:
static std::map<std::thread::id, ThreadMemoryPool> memPool;
memPool[std::this_thread::get_id()].addRef(mem);
// if memPool has no node for this thread, one is inserted,
// every thready would be guaranteed one ThreadMemoryPool object
}
有没有一种方法可以达到相同的效果……嗯,这两条线想要在不需要锁的情况下实现的一般效果?
【问题讨论】:
-
thread_local std::map<:thread::id threadmemorypool> memPool - 试试这个声明
-
@chornoxor - .... 这是一件事??这将完全消除对地图的需求!
-
编译器支持的线程局部变量比任何其他实现都高效得多,因为它们只使用段寄存器(通常是
%fs或%gs)。但请注意,线程局部变量 1. 对它们是来自可执行文件还是共享库,以及它们是从主线程还是其他线程使用稍微敏感,并且 2. 不是异步信号安全的,因为它们需要 malloc-on-first-use。
标签: c++ multithreading optimization c++14