Search code examples
c++arraysinsertsynchronize

Implementing thread-safe arrays


I want to implement a array-liked data structure allowing multiple threads to modify/insert items simultaneously. How can I obtain it in regard to performance? I implemented a wrapper class around std::vector and I used critical sections for synchronizing threads. Please have a look at my code below. Each time a thread want to work on the internal data, it may have to wait for other threads. Hence, I think its performance is NOT good. :( Is there any idea?

class parallelArray{
private:
    std::vector<int> data;
    zLock dataLock; // my predefined class for synchronizing
public:
    void insert(int val){
         dataLock.lock();
         data.push_back(val);
         dataLock.unlock();
    }

    void modify(unsigned int index, int newVal){
         dataLock.lock();
         data[index]=newVal; // assuming that the index is valid
         dataLock.unlock();
    }
};

Solution

  • The best way is to use some fast reader-writer lock. You perform shared locking for read-only access and exclusive locking for writable access - this way read-only access is performed simultaneously.

    In user-mode Win32 API there are Slim Reader/Writer (SRW) Locks available in Vista and later.

    Before Vista you have to implement reader-writer lock functionality yourself that is pretty simple task. You can do it with one critical section, one event and one enum/int value. Though good implementation would require more effort - I would use hand-crafted linked list of local (stack allocated) structures to implement fair waiting queue.