Small priority queue
Keep pending jobs ordered by priority in a fixed array. A medium embedded C problem (Buffers and data structures), run and graded in the browser.
medium · Buffers and data structures · queue · scheduling
A cooperative scheduler picks the highest-priority pending job. A zero-initialised pq_t is empty.
pq_pushadds a job and returnstrue, or returnsfalsewhen the queue is full.pq_popremoves the job with the highestpriointo*idand returnstrue, or returnsfalsewhen the queue is empty. Among jobs of equal priority, the one pushed first comes out first.
Starter code
bool pq_push(pq_t *q, uint8_t prio, uint8_t id) {
return false;
}
bool pq_pop(pq_t *q, uint8_t *id) {
return false;
}Example tests
Highest priority first
pq_t q = { 0 };
pq_push(&q, 1, 10); pq_push(&q, 3, 30); pq_push(&q, 2, 20);
uint8_t id;
while (pq_pop(&q, &id)) printf("%u ", id);
printf("\n");Expected output:
30 20 10Empty queue
pq_t q = { 0 };
uint8_t id = 5;
printf("%d %u\n", pq_pop(&q, &id), id);Expected output:
0 5Learn it first
- Buffers and data structures · Ring buffers, pools, lists and bitmaps on static memory.
More Buffers and data structures problems
- Ring buffer · Implement put and get for a fixed-size FIFO.
- Fill level from two indices · Compute how many items a FIFO holds from its head and tail.
- Overwriting log buffer · Keep only the most recent entries, replacing the oldest when full.
- Fixed-size stack · Push and pop on an array-backed stack with overflow and underflow checks.
- Sorted insert into a linked list · Insert a caller-provided node into an ascending singly linked list.
- Reverse a linked list · Reverse a singly linked list in place.
- Fixed-block memory pool · Allocate and free fixed-size blocks from a static pool.
- Bitmap operations · Set, clear and test individual bits in a byte array.
- First free slot · Find the first zero bit in a bitmap of a given length.
- Sample history by age · Store the last few samples and read them back by how old they are.
- Bump allocator · Hand out aligned chunks from a static buffer.
- Fix: the console drops characters · A serial console echoes the wrong characters once its receive buffer wraps.
- An opaque FIFO module: fifo.h and fifo.c · Implement a byte FIFO whose layout only fifo.c knows: callers hold a pointer and use four functions.
- Bluetooth speaker: never overwrite unplayed audio · A sample ring buffer that refuses new samples when full instead of overwriting the ones not yet played.