CIRCLEQ_LOOP_NEXT - Linux


Overview

The CIRCLEQ_LOOP_NEXT macro in the Linux kernel is used to iterate through a circular queue. It defines a for-each loop macro that iterates over the elements of a circular queue using the next field of the queue structure.

Syntax

#define CIRCLEQ_LOOP_NEXT(head, var, field, type)  \
	for ((var) = (type *)((head)->cqh_first);     \
	     (var) != (type *)((head)->cqh_first);    \
	     (var) = (type *)((var)->field.cqe_next))
  • head is the head of the circular queue.
  • var is the variable name to use for iterating over the queue.
  • field is the name of the next field in the queue structure.
  • type is the type of the elements in the queue.

Options/Flags

None.

Examples

The following example demonstrates how to iterate through a circular queue of struct foo elements:

#include <sys/queue.h>

struct foo {
	CIRCLEQ_ENTRY(foo) entries;
	... // Other fields
};

CIRCLEQ_HEAD(foo_head, foo);

int main() {
	struct foo_head head;
	CIRCLEQ_INIT(&head);

	// Add elements to the queue
	...

	// Iterate over the queue
	struct foo *var;
	CIRCLEQ_LOOP_NEXT(&head, var, entries, struct foo) {
		// Do something with the element
		...
	}

	return 0;
}

Common Issues

One common issue when using CIRCLEQ_LOOP_NEXT is forgetting to break out of the loop if the queue is empty. This can lead to an infinite loop. To avoid this, check the queue head before entering the loop:

if (CIRCLEQ_EMPTY(&head))
	return;

Integration

CIRCLEQ_LOOP_NEXT can be used with other Linux kernel queueing macros, such as CIRCLEQ_INSERT and CIRCLEQ_REMOVE. It can also be used with the TAILQ and LIST macros.

Related Commands

  • CIRCLEQ_FIRST
  • CIRCLEQ_LAST
  • CIRCLEQ_REMOVE
  • TAILQ_LOOP_NEXT
  • LIST_LOOP_NEXT