开发者

Do I need to use Mutex with object instances?

Do I need to use Mutex with object instances that may be concurrently updating a different object instance?

Here is an example:


I have 5 Pen object instances, 50 Author threads, and 3 Paper object instances.

Any number of Authors may be using any number of Pens to write on any given paper. I have created blocking queue to protect the Pen objects being accessed by Authors. However, the Pen instances need to take data 开发者_运维问答from Author threads and append it to the (specified) Paper instance.

Question : Do I need to block the write action of the Pen before updating the Paper instance?


You might have to synchronize the append action of the paper or block access otherwise, since you could have 5 Authors trying to concurrently write to one paper. So whenever a paper is being accessed by an Author you'd need to block it for the others.

If one Author can use multiple pens (of which I can't get the sense right now ;) ) you might also prevent multiple pens to write to the paper concurrently, so put a synchronized(pen) on the paper's write/append method.


Why would your Pen objects have any state? It seems to me that Paper is the state holder. Pen for some reason is a limited resource ok, but I don't see why you need to have state in it.

If your Pen is stateless, or at least has immutable state, then there is no need for it to have any locks at all.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜