Main Page | Modules | Alphabetical List | Data Structures | Directories | File List | Data Fields | Globals | Related Pages | Examples

events/events.c

This sample demonstrates the usage of Nut/OS event queues. It further shows how an event queue can be used as a mutual exclusion semaphore.

Two additional threads are started, one with a higher and another one with a lower priority than the main thread.

The results are printed on the debug device. Each thread prints the current action in one of three columns. The first column is used by the highest priority, the last column by the lowest priority thread.

#include <cfg/os.h>

#include <stdio.h>
#include <io.h>

#include <dev/board.h>

#include <sys/thread.h>
#include <sys/timer.h>
#include <sys/event.h>

/*
 * A global event queue, used as a mutex semaphore.
 */
static HANDLE mutex;

/*
 * High priority background thread. 
 */
THREAD(High, arg)
{
    NutThreadSetPriority(32);
    for(;;) {
        puts("Request");
        if (NutEventWait(&mutex, 2000)) {
            puts("Timeout");
        }
        else {
            puts("Acquired");
            NutSleep(2500);
            puts("Release");
            NutEventPost(&mutex);
        }
        NutSleep(1000);
    }
}

/*
 * Low priority background thread. 
 */
THREAD(Low, arg)
{
    NutThreadSetPriority(96);
    for(;;) {
        puts("                  Request");
        if (NutEventWait(&mutex, 3000)) {
            puts("                  Timeout");
        }
        else {
            puts("                  Acquired");
            NutSleep(3500);
            puts("                  Release");
            NutEventPost(&mutex);
        }
    }
}

/*
 * Main application routine. 
 */
int main(void)
{
    u_long baud = 115200;

    /*
     * Register the UART device, open it, assign stdout to it and set 
     * the baudrate.
     */
    NutRegisterDevice(&DEV_DEBUG, 0, 0);
    freopen(DEV_DEBUG_NAME, "w", stdout);
    _ioctl(_fileno(stdout), UART_SETSPEED, &baud);

    /*
     * Print title.
     */
    puts("\nNut/OS Event Queue Demo");
    puts("High     Main     Low      ");

    /*
     * Post an initial event. This will put the queue into signaled 
     * state and immediately grant the next call to NutEventWait().
     */
    NutEventPost(&mutex);

    /*
     * Start two background threads.
     */
    NutThreadCreate("high", High, 0, 256);
    NutThreadCreate("low", Low, 0, 256);

    for(;;) {
        puts("         Request");
        if (NutEventWait(&mutex, 1000)) {
            puts("         Timeout");
        }
        else {
            puts("         Acquired");
            NutSleep(1500);
            puts("         Release");
            NutEventPost(&mutex);
        }
        NutSleep(1000);
    }
}

© 2000-2006 by egnite Software GmbH - visit http://www.ethernut.de/