Skip to content

Instantly share code, notes, and snippets.

View dturvene's full-sized avatar

David Turvene dturvene

  • Dahetral Systems
  • Arlington, Virginia, USA
View GitHub Profile
@dturvene
dturvene / spinlock
Created October 27, 2022 01:54
simple spinlock using C11 atomic operations
/*
* lock_t - type for the spinlock bit array
* C11 spec says to use an atomic for atomic lock value
*/
typedef atomic_uint lock_t;
/**
* lockholder - bit array marking the thread holding the spinlock
*
* This will be 0 if no thread holds lock, otherwise ONE of the defined lock
@dturvene
dturvene / logevt
Last active October 16, 2022 10:30
fast event logger using a ringbuffer
/**
* event types to log
*/
typedef enum evtid {
EVT_ENQ = 1,
EVT_DEQ = 2,
EVT_DEQ_IDLE = 3,
EVT_END = 4,
} evtid_t;
@dturvene
dturvene / ptheads_ut
Last active October 27, 2022 01:48
pthread producer/consumer ringbuffer unit test
/**
* q_consumer: pthread to call q_deq
* @arg: pthread arguments passed from pthread_create (not used)
*
* This pthread loops until the END_EL value is received. It trys to dequeue a
* value. If one is available the function logs it, otherwise it increases and
* idle counter. After a value is dequeued it will also log the idle counter.
*
* When the consumer thread starts before the producer it busy-waits
* until the first value is written by the producer.
@dturvene
dturvene / q_deq
Last active October 27, 2022 01:37
ringbuffer dequeue function
/**
* q_deq: dequeue the oldest ringbuffer element
* @sqp: the simple queue context structure
* @valp: return the value in the current deq element
*
* Logic:
* - If no valid elements, return -1
* - get value from bufs element
* - mark queue element as invalid (for debugging) and decrement counter
* - if last element then wrap to first, otherwise move to next element
@dturvene
dturvene / struct sq
Last active October 27, 2022 01:40
ringbuffer data structure and instantiation
/* Fixed size of the array used for queuing */
#define QDEPTH 4096
/**
* struct sq - simple queue
* @bufs: fix array of buffers
* @enq: pointer to the bufs element to fill for the newest value,
* the element will either be invalid or, if valid, the
* oldest filled.
* @deq: pointer to the bufs element to drain next,
@dturvene
dturvene / q_enq
Last active October 27, 2022 01:36
ringbuffer enqueue function
/**
* q_enq: enqueue a new value into the oldest ringbuffer element
* @sqp: the simple queue context structure
* @val: value to enter into current bufs element
*
* Logic:
* - update element value and wrap or increment enq pointer
* - if all bufs are being used then move the deq pointer to the
* current oldest (one more than the newest!),
* if bufs still available then increment buf count