#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

static pthread_t WorkerThread;
static const char DbConn[] = "dbConn";
static int Task = 0;

#define DBHOST "localhost"
#define DBNAME "somename"
#define DBUSER "someuser"
#define DBPORT 5432

void *Work()
{  
  EXEC SQL BEGIN DECLARE SECTION;
    int val = 0;
    const char *_thisDbConn = DbConn;
  EXEC SQL END DECLARE SECTION; 
  pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  EXEC SQL AT :_thisDbConn SELECT 2+2 INTO :val;
  printf("2+2=%d.\n", val);
  sleep(100);
  pthread_exit(NULL);
}

int PerformTask(int TaskId)
{
  void *retval;
  char *_dbname = NULL;
  EXEC SQL BEGIN DECLARE SECTION;
    const char *dbname = _dbname;
    const char *dbuser = DBUSER;
    const char *_thisDbConn = DbConn;
  EXEC SQL END DECLARE SECTION;
  int Len = strlen(DBHOST) + strlen(DBNAME) + /* port */ 5 + /* Div */ 5;
  _dbname = (char *) malloc(Len);
  snprintf(_dbname, Len - 1, "%s@%s:%d", DBNAME, DBHOST, 5432);
  dbname = _dbname;
  EXEC SQL CONNECT TO :dbname AS :_thisDbConn USER :dbuser;
  Task = TaskId;
  pthread_create( &WorkerThread, NULL, Work, NULL );
  sleep(10);
  pthread_cancel(WorkerThread);
  pthread_join(WorkerThread, &retval);
  EXEC SQL DISCONNECT :_thisDbConn;
  free(_dbname);
  return 0;
}

int main(int argc, char **argv)
{
  PerformTask( 25 );
  return 0;
}