How can I use something like std::vector?

后端 未结 6 2174
暖寄归人
暖寄归人 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 06:52

    If efficiency is such a problem, I assume that you have only very small data structures which are changed very often. It is then probably better to use Atomic Compare And Swap (and other atomic operations) instead of using mutexes, specifically std::atomic_compare_exchange_strong

    0 讨论(0)
  • 2020-11-29 07:05

    vector requires that the values are movable, in order to maintain a contiguous array of values as it grows. You could create a vector containing mutexes, but you couldn't do anything that might need to resize it.

    Other containers don't have that requirement; either deque or [forward_]list should work, as long as you construct the mutexes in place either during construction, or by using emplace() or resize(). Functions such as insert() and push_back() will not work.

    Alternatively, you could add an extra level of indirection and store unique_ptr; but your comment in another answer indicates that you believe the extra cost of dynamic allocation to be unacceptable.

    0 讨论(0)
  • 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<std::mutex, 32> 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.

    0 讨论(0)
  • 2020-11-29 07:09

    If you want to create a certain length:

    std::vector<std::mutex> mutexes;
    ...
    size_t count = 4;
    std::vector<std::mutex> list(count);
    
    mutexes.swap(list);
    
    0 讨论(0)
  • 2020-11-29 07:16

    You could use std::unique_ptr<std::mutex> instead of std::mutex. unique_ptrs are movable.

    0 讨论(0)
  • 2020-11-29 07:17

    How about declaring each mutex as a pointer?

    std::vector<std::mutex *> my_mutexes(10)
    //Initialize mutexes
    for(int i=0;i<10;++i) my_mutexes[i] = new std::mutex();
    
    //Release mutexes
    for(int i=0;i<10;++i) delete my_mutexes[i];
    
    0 讨论(0)
提交回复
热议问题