如何在不同步的情况下创建线程本地内存

时间:2019-01-07 23:43:40

标签: c++ multithreading optimization c++14

我想给进入函数的每个线程一个仅它会使用的对象(在这种情况下,它代表一个内存页面)。这是为了帮助减少程序瓶颈的同步,因此理想情况下它本身不需要锁定互斥锁。

我要做什么的极简主义示例(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

}

是否有一种方法可以实现相同的...这两行希望完成而无需锁定的一般效果?

1 个答案:

答案 0 :(得分:1)

您的解决方案将对所有线程使用相同的memPool,并且其修改不是线程安全的。

如果要具有memPool的线程本地实例,则必须使用 thread_local说明符:

thread_local std::map<std::thread::id, ThreadMemoryPool> memPool;

在这种情况下,每个线程将使用其自己的memPool实例。