André Moreira
André Moreira

Reputation: 1699

Multithreading - In an array what should I protect?

I'm working on some code that has a global array that can be accessed by two threads for reading writing purposes.

There will be no batch processing where a range of indexes are read or written, so I'm trying to figure out if I should lock the entire array or only the array index I am currently using.

The easiest solution would be to consider the array a CS and put a big fat lock around it, but can I avoid this and just lock an index?

Cheers.

Upvotes: 2

Views: 1589

Answers (3)

juanchopanza
juanchopanza

Reputation: 227370

There is no way of knowing what will be optimal unless you profile under realistic running conditions. I would suggest implementing an array-like class, where you can lock a varying number of elements in groups. Then you fine-tune the size of these groups.

Another option would be to enqueue all read/write operations using an active object. This would make all access sequential, and means you could use a non-concurrent array type to store the data. It would require some sort of concurrent queue data structure under the hood.

Upvotes: 1

Deamonpog
Deamonpog

Reputation: 815

If this is C++ i suggest you to use STL containers. std::vector or something else which suits your job. They are fast, easy to use, no memory leaks.

If you want to do it all by your self, then of course one method will be to use a single mutex ( which is bad ). or you can use some reader writer thingy for the whole array.

I think its not feasible to make each element of an array thread safe with its own lock!! that would eat your memory. Check the link and there are 3 solutions with different out comes. Test them out and use the best for your case. ( don't think like "ok i think my program needs the readers preference algorithm". try using it in your system and decide. because we really cant assume such things sometimes )

Upvotes: 1

Alexandre Vinçon
Alexandre Vinçon

Reputation: 954

Locking one index implies that you can keep track of which thread is accessing what part of the array. Keeping track of this information, which is shared between the reading and the writing thread, implies that you have one lock around this information. So, you still end up with a global lock. In this situation, I think that the most efficient approaches are: - using a reader/writer lock - or dividing the big array into a few subsets, each subset using a distinct lock.

Upvotes: 4

Related Questions