#include <pthread.h>
//#include <sys/dispatch.h>
#include "common.h"

static int ls;

THREAD_POOL_PARAM_T *alloc( THREAD_POOL_HANDLE_T *h ) { return (THREAD_POOL_PARAM_T*)h; };

THREAD_POOL_PARAM_T *block( THREAD_POOL_PARAM_T *p ) {
      int rs = accept( ls, NULL, NULL );
      if( rs < 0 ) errx( "accept error" ); 
      return (THREAD_POOL_PARAM_T*)rs;  
};

int handler( THREAD_POOL_PARAM_T *p ) {
    retrans( (int)p );
    close( (int)p );
    delay( 250 );
    cout << pthread_self() << flush;                      
    return 0;
};

// ретранслятор c пулом thread
int main( int argc, char *argv[] ) {
   ls = getsocket( THREAD_POOL_PORT );                  
   thread_pool_attr_t attr;
   memset( &attr, 0, sizeof( thread_pool_attr_t ) );
   attr.lo_water = 3;
   attr.hi_water = 7;
   attr.increment = 2;
   attr.maximum = 9;
   attr.handle = dispatch_create();
   attr.context_alloc = alloc;
   attr.block_func = block;
   attr.handler_func = handler;
   void *tpp = thread_pool_create( &attr, POOL_FLAG_USE_SELF ) ;
   if(  tpp == NULL ) errx( "create pool" );
   thread_pool_start( tpp );
   exit( EXIT_SUCCESS );
};

