为什么这个具有两个堆栈的队列的实现是不可变的且线程安全的?

发布于 2024-12-18 23:56:00 字数 216 浏览 2 评论 0原文

我见过这种使用两个堆栈实现队列的方法: https://stackoverflow.com/a/2050402/494094

我读到,这样队列是不可变的且线程安全的。将其与普通队列分开并使其不可变且线程安全有什么意义?

如果有人能以简单、非专业的方式解释它,我将非常感激。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

二智少女 2024-12-25 23:56:00

如何使用两个堆栈实现队列?解释了更多和有一些代码。

如果您以低级方式执行此操作,您将拥有两个内存区域和两个指针
一个指针在写入时递增,另一个指针在读取时递增。

一旦读取区域用完,就反转写入区域并交换两者。

因此,阅读不会干扰写作,反之亦然。两个操作之间唯一的联系是在“反向和交换”操作期间,然后每个人都必须等待。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文