diff --git a/src/interfaces/ecpg/ecpglib/connect.c b/src/interfaces/ecpg/ecpglib/connect.c
index 8dfcabe3b5..90f2ba9701 100644
--- a/src/interfaces/ecpg/ecpglib/connect.c
+++ b/src/interfaces/ecpg/ecpglib/connect.c
@@ -40,6 +40,8 @@ ecpg_get_connection_nr(const char *connection_name)
 	if ((connection_name == NULL) || (strcmp(connection_name, "CURRENT") == 0))
 	{
 #ifdef ENABLE_THREAD_SAFETY
+		ecpg_pthreads_init();	/* ensure actual_connection_key is valid */
+
 		ret = pthread_getspecific(actual_connection_key);
 
 		/*
@@ -78,6 +78,8 @@ ecpg_get_connection(const char *connection_name)
 	if ((connection_name == NULL) || (strcmp(connection_name, "CURRENT") == 0))
 	{
 #ifdef ENABLE_THREAD_SAFETY
+		ecpg_pthreads_init();	/* ensure actual_connection_key is valid */
+
 		ret = pthread_getspecific(actual_connection_key);
 
 		/*
