/*
 * RTLinux semaphore test example
 *
 *  (C) FSMLabs  2000. Michael Barabanov <baraban@fsmlabs.com>
 *  Released under the GNU GENERAL PUBLIC LICENSE Version 2, June 1991
 */

#include <rtl.h>
#include <time.h>
#include <pthread.h>
#include <semaphore.h>

#define NTHREAD 6
static pthread_t threads[NTHREAD];
static sem_t sem;

static void * start_routine(void *arg)
{
	int ret;
	int taskno = (int)arg;

	rtl_printf("task %d; about to wait on semaphore\n", taskno);
	if (taskno % 2 == 0) {
		ret = sem_wait(&sem);
		rtl_printf("task %d; semaphore wait returned with %d\n", taskno, ret);
		if (ret < 0) {
			rtl_printf("task %d; errno=%d\n", taskno, errno);
		}
	} else {
		ret = sem_timedwait (&sem, hrt2ts(clock_gethrtime(CLOCK_REALTIME) + 1000000000LL * taskno));
		rtl_printf("task %d; semaphore wait returned with %d\n", taskno, ret);
		if (ret < 0) {
			rtl_printf("task %d; errno=%d\n", taskno, errno);
		}
		rtl_printf("task %d; posting the semaphore\n", taskno);
		sem_post(&sem);
	}

	return 0;
}


int init_module(void)
{
	int i;

	rtl_printf("RTLinux semaphore test starts on CPU%d\n", rtl_getcpuid());

	sem_init (&sem, 1, 1);

	for (i = 0; i < NTHREAD; i++) {
		pthread_create (&threads[i], NULL, start_routine, (void *)i);
	}

	return 0;
}


void cleanup_module(void)
{
	int i;

	for (i = 0; i < NTHREAD; i++) {
		pthread_cancel (threads[i]);
		pthread_join (threads[i], NULL);
	}

	sem_destroy(&sem);
}
