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

#if defined(__TURBOC__) || defined(__BORLANDC__)
#define STACKLEN 2048
#else
#define STACKLEN 4096
#endif


/*********************************************************/
void test(DWORD arg)
{
    int i = 0, j;
    kwindow( 1, 1, 40, 6 );
    do {
        cprintf("in thread #1.%lu %i\n\r", arg, i);
        i++;
        j++;
        rt_yield();
    } while ( 1 );

}
/*********************************************************/
void test2(DWORD arg)
{
    int i;
    kwindow( 41, 1, 80, 6 );
    for ( i = 0 ; i < 6000; ++i ) {
        cprintf("in thread #2.%lu %i\n\r", arg, i );
        rt_yield();
    }
    cprintf("done thread, exitting");
//  uncomment next line to start this thread anew each time it closes
//    rt_newthread( test2, arg+1, 16536, 0, "worker 2" );
}
/*********************************************************/

void timer(DWORD arg)
{
    time_t x;
    kwindow( 1, 16, 80, 25 );
    arg++;
    do {
        time( &x );
        gotoxy( 1, 1 );
        cprintf("%s\r\n%u blk  %lu free %lu threads     ", ctime( &x ), kblocked,kcorefree(), knumthreads());
        rt_sleep( 1000 );
    } while( 1 );
}
/*********************************************************/

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

    // changing the next line would all that is needed to make this
    // a pre-emptive multithreaded application

    kpreemptive = 0;
    kdebug = 1;
    rt_init(100);
    kwindow( 1, 6, 80, 16 );
    cputs("starting...\r\n");

    rt_newthread( timer, 0,4096, 0, "timer" );
    rt_newthread( test,  1,4096, 0, "worker 1" );
    rt_newthread( test2, 2,4096, 0, "worker 2" );

    for ( i = 0 ; i < 1000 ; ++i ) {
        rt_sleep( 10 );
        cprintf("in main %i\n\r", i);
    }
}

