Ring buffers and deques under the hood
لم يُترجم بعد؛ يُعرض باللغة الإنجليزية
عن هذا الدرس
A queue that never shifts its items. Keep them in a fixed Python list of 8 slots, remember where the front is (head) and how many there are (size), and let the % operator join the end of the list to its start. Push and pop each touch one slot, so both take the same time however long the queue is. The Software lesson "Stacks and queues" shows why list.pop(0) is slow and introduces collections.deque; this lesson builds that fast queue by hand, then adds the second end that makes a deque.
Eight slots in a ring
A queue adds at the back and takes from the front. Here it lives in a plain Python list of 8 slots, numbered 0 to 7. q.head is the slot of the front item; q.size counts the items. Both start at 0.
setup (runs before the card): from types import SimpleNamespace CAP = 8 q = SimpleNamespace(buf=[None] * CAP, head=0, size=0) slots 0:· 1:· 2:· 3:· 4:· 5:· 6:· 7:· head = 0 size = 0 tail = (0 + 0) % 8 = 0
اقرأ الدرس خطوة بخطوة
Eight slots in a ring
A queue adds at the back and takes from the front. Here it lives in a plain Python list of 8 slots, numbered 0 to 7. q.head is the slot of the front item; q.size counts the items. Both start at 0.
setup (runs before the card): from types import SimpleNamespace CAP = 8 q = SimpleNamespace(buf=[None] * CAP, head=0, size=0) slots 0:· 1:· 2:· 3:· 4:· 5:· 6:· 7:· head = 0 size = 0 tail = (0 + 0) % 8 = 0Push adds at the back
push finds the back slot: tail = (head + size) % 8. With head at 0 that gives slots 0, 1 and 2 for A, B and C. Each push writes one slot and adds 1 to size: one step, however long the queue is.
tail = (0 + 0) % 8 = 0, then 1, then 2 push(q, "A") -> slot 0 push(q, "B") -> slot 1 push(q, "C") -> slot 2 slots 0:A 1:B 2:C 3:· 4:· 5:· 6:· 7:· head = 0 size = 3 tail = (0 + 3) % 8 = 3Pop takes from the front
pop returns the item in slot head, then moves head on by one. A and B leave; head goes 0, 1, 2. Nothing else moves: C stays in slot 2. A list's pop(0) would shift every item left instead.
head = (head + 1) % 8: 0 -> 1 -> 2 pop() -> A (slot 0, head -> 1) pop() -> B (slot 1, head -> 2) slots 0:· 1:· 2:C 3:· 4:· 5:· 6:· 7:· head = 2 size = 1 tail = (2 + 1) % 8 = 3Fill to the end
Push D, E, F, G and H. They land in slots 3 to 7, the last slots of the list. Now head is 2 and size is 6, so the queue holds C to H, front to back.
push(q, "D") -> slot 3 push(q, "E") -> slot 4 push(q, "F") -> slot 5 push(q, "G") -> slot 6 push(q, "H") -> slot 7 slots 0:· 1:· 2:C 3:D 4:E 5:F 6:G 7:H head = 2 size = 6 tail = (2 + 6) % 8 = 0Wrap around with %
Push I: tail = (2 + 6) % 8 = 0. The % gives the remainder after dividing, so 8 becomes 0 and I goes back to slot 0, which A left free. The end of the list joins its start: a ring.
tail = (2 + 6) % 8 = 8 % 8 = 0 push(q, "I") -> slot 0 slots 0:I 1:· 2:C 3:D 4:E 5:F 6:G 7:H head = 2 size = 7 tail = (2 + 7) % 8 = 1Full: tail meets head
Push J into slot 1. Now size is 8 and tail = (2 + 8) % 8 = 2, the same slot as head. head and tail also meet when the queue is empty, so size is what tells full from empty.
empty: size 0, tail == head full: size 8, tail == head push(q, "J") -> slot 1 slots 0:I 1:J 2:C 3:D 4:E 5:F 6:G 7:H head = 2 size = 8 tail = (2 + 8) % 8 = 2One push too many
Push K finds size == CAP and raises an error instead of writing over C, the front item. A growing queue would copy all 8 items into a list twice as big; a bounded deque drops the oldest item instead.
size == CAP, so push raises before it writes push(q, "K") -> IndexError: full slots 0:I 1:J 2:C 3:D 4:E 5:F 6:G 7:H head = 2 size = 8 tail = (2 + 8) % 8 = 2The front wraps too
Pop six times: C, D, E, F, G and H come out. head counts 3, 4, 5, 6, 7, then (7 + 1) % 8 = 0. Now the front is I in slot 0, with J behind it.
head = (7 + 1) % 8 = 0 on the last pop pop() -> C (slot 2, head -> 3) pop() -> D (slot 3, head -> 4) pop() -> E (slot 4, head -> 5) pop() -> F (slot 5, head -> 6) pop() -> G (slot 6, head -> 7) pop() -> H (slot 7, head -> 0) slots 0:I 1:J 2:· 3:· 4:· 5:· 6:· 7:· head = 0 size = 2 tail = (0 + 2) % 8 = 2Push at the front
A deque (a double-ended queue) can also add at the front: head = (head - 1) % 8. In Python -1 % 8 is 7, so Z goes into slot 7, just before I. Both ends take one step.
push_front (not on the card): def push_front(q, x): if q.size == CAP: raise IndexError("full") q.head = (q.head - 1) % CAP q.buf[q.head] = x q.size += 1 (0 - 1) % 8 = 7 in Python push_front(q, "Z") -> slot 7 slots 0:I 1:J 2:· 3:· 4:· 5:· 6:· 7:Z head = 7 size = 3 tail = (7 + 3) % 8 = 2Python's deque
You rarely write this by hand: collections.deque has append, appendleft, pop and popleft, each O(1). Inside CPython it is a chain of 64-slot blocks rather than one ring, but the idea is the same: the ends move, the items stay.
from collections import deque d = deque("IJ") d.appendleft("Z") # deque(['Z', 'I', 'J']) d.append("L") # back d.popleft() # 'Z', the front list.pop(0) shifts every item: O(n) deque.popleft() moves none: O(1)
أسئلة سريعة: 5
اختر إجابة واحدة لكل سؤال. يمكنك تغيير اختياراتك قبل التحقق منها.
01A ring has 8 slots, head = 5 and size = 3. Which slot does the next push write?
tail = (head + size) % 8 = (5 + 3) % 8 = 0. There is no slot 8: the % wraps it round to slot 0.
02Why is pop on a ring buffer O(1), while list.pop(0) is O(n)?
In a ring buffer no item moves: only the head number changes. A list keeps item 0 at the start, so removing it means moving all the others, which takes time in proportion to n.
03In a ring where head and tail point to the same slot, how do you know whether it is full or empty?
tail = (head + size) % CAP equals head both when size is 0 and when size is CAP. Keeping size (or, like CLRS, leaving one slot always empty) is what tells the two apart.
04In Python, with CAP = 8 and head = 0, what does push_front set head to?
head = (0 - 1) % 8. Python's % takes the sign of the number after it, so -1 % 8 is 7: the new front item goes in the last slot, just before the old front.
05What does collections.deque(maxlen=3) hold after d.extend('ABCD')?
A bounded deque, once full, discards items from the opposite end. Adding D to a full deque of A, B, C pushes A out of the front, leaving B, C, D.
المسرد
- Queue
- A line of items where you add at the back and take from the front: first in, first out (FIFO).
- Ring buffer
- A fixed-size list used as a loop: when an index passes the last slot it wraps back to slot 0. Also called a circular buffer.
- head
- The slot number of the front item, the one pop takes next.
- tail
- The slot the next push writes: (head + size) % CAP, the slot just after the back item.
- % (modulo)
- The remainder after division. 8 % 8 is 0 and 9 % 8 is 1, which is what makes the indexes wrap round.
- Deque
- A double-ended queue: you can add and remove at both the front and the back. Python's version is collections.deque.
- Amortised cost
- The average cost per operation over a long run, even if a few single operations (like copying to a bigger array) are slow.
الملاحظات والمصادر
- The card's functions run as-is after three lines of setup: from types import SimpleNamespace; CAP = 8; q = SimpleNamespace(buf=[None] * CAP, head=0, size=0). push_front, used in step 9, is shown in that step's notes.
- To keep the card short, pop has no empty check. Real code starts pop with if q.size == 0: raise IndexError("empty"), which is what deque.pop does on an empty deque.
- Python's % always gives a result with the sign of the number after it, so -1 % 8 is 7. In C or Java -1 % 8 is -1, so ring code there writes (head - 1 + CAP) % CAP instead.
- A growing ring, like ResizingArrayQueue in Sedgewick and Wayne, doubles its array when full and copies the items in queue order, starting at head. That one push costs O(n), but averaged over many pushes the cost is O(1) (amortised).
- CPython builds collections.deque as a doubly linked list of fixed blocks of 64 slots (BLOCKLEN in Modules/_collectionsmodule.c), so it never has to copy everything to grow. deque(maxlen=n) is a bounded ring: once full, each new item pushes one out at the other end.
- CLRS keeps head and tail and leaves one slot empty, so a ring of n slots holds at most n - 1 items. Keeping size instead, as here, uses every slot.
- Python docs: collections.deque
- Python Language Reference §6.7: Binary arithmetic operations (the % operator)
- CPython source: Modules/_collectionsmodule.c (BLOCKLEN 64)
- Sedgewick and Wayne, Algorithms 4th ed., §1.3 Bags, Queues, and Stacks
- Sedgewick and Wayne, ResizingArrayQueue.java
- MIT 6.006 Introduction to Algorithms (Spring 2020), Lecture 2: Data Structures
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), §10.1
اختبار يتاح بعد الخطوة الأخيرة.