#include <pthread.h>
#include "common.h"

static int ntr = 3;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t condvar = PTHREAD_COND_INITIALIZER;

void* echo( void* ps ) {
    int sc = *(int*)ps, rs;
    sched_yield();
    if( ( rs = accept( sc, NULL, NULL ) ) < 0 ) errx( "accept error" ); 
    retrans( rs );
    close( rs );
    pthread_mutex_lock( &mutex );
    ntr++;
    pthread_cond_signal( &condvar );
    pthread_mutex_unlock( &mutex );
    if( debug ) cout << pthread_self() << '.' << flush;
    delay( 250 );  // пауза 250 usec.
    return NULL;
}

// ретранслятор c предварительным pthread_create()
int main( int argc, char *argv[] ) {
   int ls = getsocket( PRETHREAD_PORT ), rs;               
   setv( argc, argv );
   while( true ) {
      pthread_t tid;
      if( pthread_create( &tid, NULL, &echo, &ls ) != EOK ) errx( "thread create error" );
      sched_yield();       
      pthread_mutex_lock( &mutex );
      ntr--;
      while( ntr <= 0 ) pthread_cond_wait( &condvar, &mutex );
      pthread_mutex_unlock( &mutex );
   };
   exit( EXIT_SUCCESS );
};

