/**************************************************************************/
/* test8                                                                  */
/* This example shows how priorities work.                                */
/*                                                                        */
/**************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <setjmp.h>
#include <dos.h>
#include <mem.h>
#include <conio.h>
#include <rtos.h>

#define MAXTHREADS 4

thread_x *th[ MAXTHREADS ];

/*********************************************************/
void test(DWORD arg)
{
    int i, j;

    kwindow( arg*80/MAXTHREADS+1, 1, (arg+1)*80/MAXTHREADS , 16 );
    do {
        cprintf("in thread #%lu %i\n\r", arg, i);
        i = ( i + 1 ) % 1000;
        rt_yield();
    } while ( 1 );
}

/*--------------------------------------------------------------------*/

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

    clrscr();

//    kpreemptive = 1;
    kdebug = 1;
    rt_init( 100 );

    kwindow( 1, 17, 79, 25 );
    cputs("starting all threads...\r\n");

    for ( i = 0 ; i < MAXTHREADS ; ++i )
        th[i] = rt_newthread( test,  i ,4096, 96, "worker n" );

    /* first state - all running */
    cprintf("They are all running at the same priority for now\r\n");
    for ( j = 4 ; j ; --j ) {
        cprintf(" %u \r", j );
        rt_sleep( 1000 );
    }

    /* second state - cycle through the children, one at a time */
    /*                by setting its priority above others      */
    for ( j = 0 ; j < MAXTHREADS ; ++j ) {
        cprintf("giving priority to thread %u \r", j);
        for ( i = 0 ; i < MAXTHREADS ; ++i )
            rt_setpriority( th[i], (i==j) ? 65 : 96 );
        rt_sleep( 4 * 1000 );
    }
    /* third state  - start with one thread and keep adding one */
    /*                by increasing its priority to match first */
    for ( j = 0 ; j < MAXTHREADS ; ++j ) {
        cprintf("bumping up priority on thread %u \r", j);
        rt_setpriority( th[j], 64 );
        rt_sleep( 4 * 1000 );
    }

}
