1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
|
/*
* 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);
}
|