/**************************************************************************/
/* test13                                                                 */
/* This example demonstrates rt_yield(), rt_sleep(0), rt_sleep(500)       */
/**************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <rtos.h>

/*********************************************************/
void test(DWORD arg)
{
    int i = 0;
    kwindow( 1, 1, 80, 6 );
    while ( 1 ) {
        cprintf("%u ", i++);
        switch ( arg ) {
            case 0 : rt_yield(); break;
            case 1 : rt_sleep( 0 ); break;
            case 2 : rt_sleep( 100 );
        }
    }
}

/*********************************************************/
void heartbeat(DWORD arg)
{
    int i = 0;

    kwindow( 1, 6, 80, 12 );
    cputs("Heartbeat thread\r\n");

    /* run at low priority */
    rt_setpriority( NULL, 127 );

    while ( 1 ) {
        cprintf("%u ", i++);
        rt_sleep(0);
    }
}

void runtest( DWORD testnum, char *s )
{
    void *x, *hb;

    hb = rt_newthread( heartbeat, 0, 4096, 0, "heartbeat");
    x = rt_newthread( test,  testnum ,4096, 0, "worker" );
    cputs(s);

    /* let the test run, then stop it */
    rt_sleep( 3000 );
    kdestroythread( x );
    kdestroythread( hb );

    /* signal the user */
    sound( 100 );
    rt_sleep( 20 );
    nosound();
}
/*--------------------------------------------------------------------*/

main(int argc, char **argv)
{
    int i;

    kdebug = 1;
    rt_init( 100 );
    kwindow( 1, 12, 80, 25 );

    rt_timerfreq( 100 );

    cputs("The top window executes at normal priority, the second window is low priority\r\n");
    cputs("This demonstrates the effects of a normal program yielding and sleeping\r\n\n");

    /* rt_yield() */
    runtest( 0, "Top thread is calling rt_yield()\r\n"
                "Only yields to similar or higher priority threads. Heartbeat does not qualify.\r\n\n");

    /* rt_sleep( 0 ) */
    runtest( 1, "Now, top thread is calling rt_sleep( 0 )\r\n"
                "Yields current time slice, even low priority threads get a chance\r\n\n");

    /* rt_sleep( 1 ) */
    runtest( 2, "Now, top thread is calling rt_sleep( 100 )\r\n"
                "Sleeps for a spell, allowing other threads to execute for 100ms\n");

}


