Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Standard way to make STL objects threadsafe?

I need several STL containers, threadsafe.

Basically I was thinking I just need 2 methods added to each of the STL container objects,

.lock()

.unlock()

I could also break it into

.lockForReading()
.unlockForReading()
.lockForWriting()
.unlockForWriting()

The way that would work is any number of locks for parallel reading are acceptable, but if there's a lock for writing then reading AND writing are blocked.

An attempt to lock for writing waits until the lockForReading semaphore drops to 0.

Is there a standard way to do this?

Is how I'm planning on doing this wrong or shortsighted?

like image 675
bobobobo Avatar asked Dec 13 '22 12:12

bobobobo


1 Answers

This is really kind of bad. External code will not recognize or understand your threading semantics, and the ease of availability of aliases to objects in the containers makes them poor thread-safe interfaces.

Thread-safety occurs at design time. You can't solve thread safety by throwing locks at the problem. You solve thread safety by not having two threads writing to the same data at the same time- in the general case, of course. However, it is not the responsibility of a specific object to handle thread safety, except direct threading synchronization primitives.

You can have concurrent containers, designed to allow concurrent use. However, their interfaces are vastly different to what's offered by the Standard containers. Less aliases to objects in the container, for example, and each individual operation is encapsulated.

like image 146
Puppy Avatar answered Dec 28 '22 04:12

Puppy