October 6, 2016

A Kyu tutorial - blink an LED using a semaphore

Once again, this example behaves exactly like the first two, but it demonstrates the use of a semaphore for synchronization. Using a semaphore means that we don't need to make any calls to any "thr_" family functions and don't need a handle to the current thread at all.
#include "kyu.h"
#include "thread.h"

static struct sem *user_sem;
static int count;

static void
ticker ( void )
{
	++count;
	if ( count > 49 ) {
	    sem_unblock ( user_sem );
	    count = 0;
	}
}

static int led = 0;

static void
blinker ( int xx )
{
	gpio_led_set ( led );
	led = (led+1) % 2;

	sem_block_q ( user_sem );
}

void
user_init ( int xx )
{

	count = 0;
	user_sem = sem_signal_new ( SEM_PRIO );
	gpio_led_init ();
	timer_hookup ( ticker );

	sem_block_c ( user_sem, blinker, 0 );
}
Kyu provides binary semaphores in two flavors: signalling and mutex semaphores. The only difference is their initial state, but the name of the creator function (in this case sem_signal_new() makes it clear which type is being created. Note that the semaphore blocking and unblocking functions have endings "_c" and "_q" just like the thr_block and thr_unblock calls.


Have any comments? Questions? Drop me a line!

Kyu / tom@mmto.org