This is a design question that has been bugging me for a while now. It is pretty simple really, when you provide datastructure libraries do you build in the thread-safety primitives or just provide the constructs and let the system using it decide on how to implement the actual operations.
A quick example, a Circular buffer which supports a Producer, Consumer model. 2 Methods, Get and Write, each updates a global variable fill count. Now, do you just provide the mutexes to lock and let the code using the buffer grab the mutexes OR do you the locking internally and provide mutual exclusion out of the box.
STL seems to take the approach of doing it externally, but there are performance reasons of why you would want to provide finer grained locking.
Thoughts ?
IMHO there is no clear winner to this discussions. There are pros and cons on either side of the board:
Having synchronization as a part of the API (inside the module):
Letting the caller synchronize
You could make a decision based on the case:
Hope this helps!
I was thinking about the exact problem sometime ago. So I went ahead and wrote some sample code to understand the advantages and disadvantages of various approaches. So, instead of giving a theoretical answer, let me give you some code for the same problem that you have mentioned in the OP i.e. circular buffer (queue) with multiple producer and consumer.
Here it is.
Perhaps looking at the code may give you some clarification. I shall add more points if need be.. but for now, look at the code and derive the obvious!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With