LInux/c++, how to protect two data structures at same time?

I'm developing some programs with c/c++ in Linux. my question is:

  • I have an upper-level class called Vault, inside of which there are an OrderMap which uses unordered_map as data structure and a OrderBook, which has 2 std::list in side.
  • Both the OrderMap and OrderBook stores Order* as the element, they share an Order object which is allocated on heap. So either the OrderBook or the OrderMap modifies the order within.
  • I have two threads that will do read and write operations on them. the 2 threads can insert/modify/retrieve(read)/delete the elements.
  • My Question is: how can I protect this big structure of "Vault"? I can actually protect the map or list, but I don't know how to protect them both at the same time.

    anybody gives me some ideas?


    Add a mutex and lock it before accessing any of the two.

    Make them private, so you know accesses are made via your member functions (which have proper locks)

    Consider using std::shared_ptr instead of Order *


    I don't think I've ever seen a multi-thread usage of an order book. I really think you'd be better off using it in one thread only.

    But, to get back to your question, I'll assume you're staying with 2 threads for whatever reasons.
    This data structure is too complex to make it lock free. So these are the multi-thread options I can see:
    1. If you use a single Vault instance for both threads you will have to lock around it. I assume you don't care to burn some cpu time, so I strongly suggest you use a spin lock, not a mutex.
    2. If you can allow having 2 Vault instances this can improve things as every thread can keep it's own private instance and exchange modifications with the other thread using some other means: a lock free queue, or something else.
    3. If your book is fast enough to copy, you can have a single central Vault pointer, make a copy on every update, or a group of updates, CAS onto that central pointer, and reuse the old one to not have to allocate every time. You'll end up with one spare instance per thread. Like this:

    Vault* old_ptr = centralVault;
    Vault* new_ptr = cachedVault ? cachedVault : new Vault;
    do {
        *new_ptr = *old_ptr;
        makeChanges(new_ptr);
    }
    while( !cas(&centralVault, old_ptr, new_ptr) );
    cachedVault = old_ptr;
    
    链接地址: http://www.djcxy.com/p/87908.html

    上一篇: C ++使用struct的嵌套数据结构

    下一篇: LInux / c ++,如何同时保护两个数据结构?