为什么具有两个堆栈的队列的这种实现是不可变的且线程安全的? [英] Why is this implementation of a queue with two stacks immutable and thread safe?

查看:325
本文介绍了为什么具有两个堆栈的队列的这种实现是不可变的且线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了用两个堆栈实现队列的这种方式: 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.

推荐答案

如何使用两个堆栈实现队列?进一步说明并提供一些代码.

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.

这篇关于为什么具有两个堆栈的队列的这种实现是不可变的且线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆