Why is this implementation of a queue with two stacks immutable and thread safe?

99封情书 提交于 2019-12-13 07:12:18

问题


I've seen this way of implementing a queue with two stacks: https://stackoverflow.com/a/2050402/494094

And I've read that this way the queue is immutable and thread-safe. What's the point that separates this from a normal queue and makes it immutable and thread-safe?

I'd really appreciate it if someone could explain it in a simple, non-professional way.


回答1:


How to implement a queue using two stacks? explains more and has some code.

If you do this in a low-level way you will have two memory areas and two pointers One pointer increments when you write, the other when you read

Once the read area is used up, you reverse the write area and swap the two.

So there is no chance of the reading interfering with the writing and vice versa. The only connection between the two operations is during the "reverse and swap" operation, and then everybody has to wait.



来源:https://stackoverflow.com/questions/8357459/why-is-this-implementation-of-a-queue-with-two-stacks-immutable-and-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!