@@ -28,22 +28,52 @@ func NewLockFreeQ[T any]() *LockFreeQ[T] {
2828 }
2929}
3030
31- // Enqueue adds a series of Request to the queue
32- // Enqueue is thread safe; it uses atomic operations to add to the queue
31+ // Enqueue adds a value to the end of the queue in a lock-free, thread-safe manner.
32+ //
33+ // This method performs the following steps:
34+ // - Allocates a new node containing the provided value
35+ // - Atomically swaps the queue's tail pointer to the new node
36+ // - If the queue was empty, links the head to the new node
37+ // - Otherwise, links the previous tail's next pointer to the new node
38+ //
39+ // Parameters:
40+ // - v: the value to enqueue; may be any type supported by the generic parameter T
41+ //
42+ // Returns:
43+ // - None
44+ //
45+ // Side Effects:
46+ // - Mutates the internal state of the queue by appending a new node
47+ // - Uses atomic operations to ensure thread safety for concurrent enqueues
3348func (q * LockFreeQ [T ]) Enqueue (v T ) {
34- node := & node [T ]{value : v }
35- prev := q .tail .Swap (node )
49+ newNode := & node [T ]{value : v }
50+ prev := q .tail .Swap (newNode )
3651
3752 if prev == nil {
38- q .head .next .Store (node )
53+ q .head .next .Store (newNode )
3954 return
4055 }
4156
42- prev .next .Store (node )
57+ prev .next .Store (newNode )
4358}
4459
45- // Dequeue removes a Request from the queue
46- // Dequeue is not thread safe, it should only be called from a single thread !!!
60+ // Dequeue removes and returns the value at the front of the queue in a lock-free queue.
61+ //
62+ // This method performs the following steps:
63+ // - Loads the next node after the current head
64+ // - If the next node is nil, the queue is empty and nil is returned
65+ // - Otherwise, advances the head pointer to the next node
66+ //
67+ // - Returns a pointer to the value stored in the dequeued node
68+ //
69+ // Parameters:
70+ // - None
71+ //
72+ // Returns:
73+ // - Pointer to the value of type T at the front of the queue, or nil if the queue is empty
74+ //
75+ // Side Effects:
76+ // - Mutates the internal state of the queue by advancing the head pointer
4777func (q * LockFreeQ [T ]) Dequeue () * T {
4878 next := q .head .next .Load ()
4979
@@ -56,7 +86,21 @@ func (q *LockFreeQ[T]) Dequeue() *T {
5686 return & next .value
5787}
5888
59- // IsEmpty determines if the queue is empty
89+ // IsEmpty reports whether the queue contains any elements.
90+ //
91+ // This method performs the following steps:
92+ // - Loads the next node after the current head
93+ // - If the next node is nil, the queue is empty
94+ // - Otherwise, the queue contains at least one element
95+ //
96+ // Parameters:
97+ // - None
98+ //
99+ // Returns:
100+ // - true if the queue is empty; false otherwise
101+ //
102+ // Side Effects:
103+ // - None
60104func (q * LockFreeQ [T ]) IsEmpty () bool {
61105 return q .head .next .Load () == nil
62106}
0 commit comments