Skip to content

Instantly share code, notes, and snippets.

@mcastorina
Created January 18, 2016 04:21
Show Gist options
  • Save mcastorina/fb76b3d9e02abc37db36 to your computer and use it in GitHub Desktop.
Save mcastorina/fb76b3d9e02abc37db36 to your computer and use it in GitHub Desktop.
A queue struct for tasks.
#include "queue.h"
void queue_init(struct queue *q) {
q->start = 0;
q->end = 0;
}
uint8_t queue_enqueue(struct queue *q, void (*task)(void*), void *arg) {
if (queue_full(q))
return 1;
q->tasks[q->end] = task;
q->task_args[q->end++] = arg;
q->end %= QUEUE_SIZE;
return 0;
}
uint8_t queue_dequeue(struct queue *q) {
if (queue_empty(q))
return 1;
q->tasks[q->start](q->task_args[q->start++]);
q->start %= QUEUE_SIZE;
return 0;
}
uint8_t queue_full(struct queue *q) {
return ((q->end + 1) % QUEUE_SIZE == q->start);
}
uint8_t queue_empty(struct queue *q) {
return (q->end == q->start);
}
#include <stdint.h>
#ifndef __QUEUE_H__
#define __QUEUE_H__
#define QUEUE_SIZE (32)
struct queue {
uint8_t start;
uint8_t end;
void (*tasks[QUEUE_SIZE])(void*); /* Functions to run */
void *task_args[QUEUE_SIZE]; /* Arguments to function */
};
/*
* Initialize queue
* q: queue struct pointer
* Return
* None
*/
void queue_init(struct queue *q);
/*
* Enqueue a task
* q: queue struct pointer
* task: pointer to function to run
* arg: argument to pass to task
* Return
* 1: queue is full
* 0: success
*/
uint8_t queue_enqueue(struct queue *q, void (*task)(void*), void *arg);
/*
* Run the next task
* q: queue struct pointer
* Return
* 1: queue is empty
* 0: success
*/
uint8_t queue_dequeue(struct queue *q);
/*
* Checks if the queue is full
* q: queue struct pointer
* Return
* non-zero: queue is full
* 0: queue is not full
*/
uint8_t queue_full(struct queue *q);
/*
* Checks if the queue is empty
* q: queue struct pointer
* Return
* non-zero: queue is empty
* 0: queue is not empty
*/
uint8_t queue_empty(struct queue *q);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment