How can I use something like std::vector?

后端 未结 6 2179
暖寄归人
暖寄归人 2020-11-29 06:33

I have a large, but potentially varying, number of objects which are concurrently written into. I want to protect that access with mutexes. To that end, I thought I use a

6条回答
  •  北海茫月
    2020-11-29 07:08

    I suggest using a fixed mutex pool. Keep a fixed array of std::mutex and select which one to lock based on the address of the object like you might do with a hash table.

    std::array mutexes;
    
    std::mutex &m = mutexes[hashof(objectPtr) % mutexes.size()];
    
    m.lock();
    

    The hashof function could be something simple that shifts the pointer value over a few bits. This way you only have to initialize the mutexes once and you avoid the copy of resizing the vector.

提交回复
热议问题