/**************************************************************************/
/* test17 - shows results of slow message reads                           */
/*          Suppose you have two threads communicating using the messaging*/
/*          functions.  If the reader reads more slowly than the writer   */
/*          sends, soon the message queue will become depleted.           */
/*          Then other operations - like rt_sleep - may be affected as    */
/*          there is no space on the message queue for their messages     */
/*          To demonstrate this, we are using a very small message queue  */
/*          and note that the sender eventually locks in at 5 messages    */
/*          ahead of the sender.  rt_sleep( 200 ) will wait longer than   */
/*          200 ms because sleep has no messages available to inform the  */
/*          sleeping client to wake up.                                   */
/**************************************************************************/

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

void *peer = NULL;

void switcher1(DWORD arg)
{
    int x;

#if defined(__TURBOC__)||defined(__BORLANDC__)
    randomize();
#else
    srand( time( 0 ) );
#endif
    

    do {
        x = rand();
        cprintf( " sending %u ", x );
        kwritemessage( peer, x, 0 );
        rt_sleep(200);
    } while ( 1 );
}
void switcher2(DWORD arg)
{
    int x;
    DWORD y;
    do {
        if (kgetmessage( &x, &y ) ) {
            cprintf(" read %u \r\n", x );
            for(y=0; y<=20000000L; y++); // for instance waiting for a serial port answer
            printf("Oo");
        }
     } while ( 1 );
}

main()
{
    kdebug = 1;
    kpreemptive = 1;  // preemtive because switcher2 does not switch away
    rt_init(5);       // a VERY small message queue size to demo this problem
    cputs("starting...\r\n");
    peer = rt_newthread( switcher2, 2, 4096, 1, "worker2" );
    rt_newthread( switcher1, 1, 4096, 1, "worker1" );
    while ( 1 ) rt_sleep( 10000 );
}

