#include <stdio.h>
#include <stdlib.h>


#include <pthread.h>
#include "/usr/include/postgresql/libpq-fe.h"


static void
exit_nicely(PGconn *conn)
{
	PQfinish(conn);
	exit(1);
}


void *print_message_function( void *ptr );

main()
{
	int MAX = 10;
	pthread_t thread[MAX];
	const char *message = "Hello Wordl!";
	int  iret[MAX];

	/* Create independent threads each of which will execute function */
	int i;
	for ( i = 0; i < MAX; i++ )		
	{
		iret[i] = pthread_create( &thread[i], NULL, print_message_function, (void*) message);
		if(iret[i])
		{
			fprintf(stderr,"Error, return code: %d\n", iret[i]);
			exit(EXIT_FAILURE);
		}
	}
	
	for ( i = 0; i < MAX; i++ )		
		printf("pthread_create(), thread %d returns: %d\n", i, iret[i]);


	for ( i = 0; i < MAX; i++ )		
		pthread_join( thread[i], NULL);

	exit(EXIT_SUCCESS);
}

void *print_message_function( void *ptr )
{
	char *message;
	message = (char *) ptr;
	printf("%s \n", message);

	// database variable
	const char	*conninfo;
	PGconn		*conn;
	PGresult	*res;
	int		nFields,
			nRows;
	int		i,
			j;
	int		result_ok = 0;

	conninfo = "host=127.0.0.1 dbname=postgres user=postgres password=XXX port=5432";

	/* Make a connection to the database */
	conn = PQconnectdb(conninfo);

	/* Check to see that the backend connection was successfully made */
	if (PQstatus(conn) != CONNECTION_OK)
	{
		fprintf(stderr, "Connection to database failed: %s",
				PQerrorMessage(conn));
		exit_nicely(conn);
	}

	/* Start a transaction block */
	res = PQexec(conn, "BEGIN");
	PQclear(res);
	/* disable notice */
	res = PQexec(conn, "SET client_min_messages TO NOTICE;");
	PQclear(res);
	/* end the transaction */
	res = PQexec(conn, "END");
	PQclear(res);

	/* close the connection to the database and clean-up */
	PQfinish(conn);

}

















