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

static queue<int> events;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* reply( void* ) {
   int rsq;
   while( true ) {
      if( events.empty() ) continue;
      pthread_mutex_lock( &mutex );
      rsq = events.front();
      events.pop();
      if( debug ) cout << '-' << rsq << '.' << flush;
      pthread_mutex_unlock( &mutex );
      retrans( rsq );
      close( rsq );
   };
}
    
// последовательный ретранслятор c очередью обслуживания
int main( int argc, char *argv[] ) {
   int ls = getsocket( QUEUE_PORT );
   setv( argc, argv );
   pthread_t tid;
   if( pthread_create( &tid, NULL, &reply, NULL ) != EOK )
      errx( "thread create error" );
   while( true ) {
      int rs = accept( ls, NULL, NULL );
      if( rs < 0 ) errx( "accept error" ); 
      pthread_mutex_lock( &mutex );
      events.push( rs );
      if( debug ) cout << '+' << rs << '.' << flush;
      pthread_mutex_unlock( &mutex );
   };
   exit( EXIT_SUCCESS );
};
