开发者

Implementing thread-safe arrays

开发者 https://www.devze.com 2023-04-07 07:11 出处:网络
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

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.unlo开发者_StackOverflow中文版ck();
    }

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


Take a look at shared_mutex in the Boost library. This allows you to have multiple readers, but only one writer

http://www.boost.org/doc/libs/1_47_0/doc/html/thread/synchronization.html#thread.synchronization.mutex_types.shared_mutex


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消