diff --git a/src/interfaces/libpq/fe-secure.c b/src/interfaces/libpq/fe-secure.c
new file mode 100644
index 3bd0113..e14c301 100644
*** a/src/interfaces/libpq/fe-secure.c
--- b/src/interfaces/libpq/fe-secure.c
*************** destroy_ssl_system(void)
*** 1009,1017 ****
  {
  #ifdef ENABLE_THREAD_SAFETY
  	/* Mutex is created in initialize_ssl_system() */
- 	if (pthread_mutex_lock(&ssl_config_mutex))
- 		return;
- 
  	if (pq_init_crypto_lib && ssl_open_connections > 0)
  		--ssl_open_connections;
  
--- 1009,1014 ----
*************** destroy_ssl_system(void)
*** 1031,1037 ****
  		 */
  	}
  
- 	pthread_mutex_unlock(&ssl_config_mutex);
  #endif
  }
  
--- 1028,1033 ----
*************** open_client_SSL(PGconn *conn)
*** 1537,1542 ****
--- 1533,1543 ----
  static void
  close_SSL(PGconn *conn)
  {
+ #ifdef ENABLE_THREAD_SAFETY
+ 	if (pthread_mutex_lock(&ssl_config_mutex))
+ 		return;
+ #endif
+ 
  	if (conn->ssl)
  	{
  		DECLARE_SIGPIPE_INFO(spinfo);
*************** close_SSL(PGconn *conn)
*** 1565,1570 ****
--- 1566,1575 ----
  		conn->engine = NULL;
  	}
  #endif
+ 
+ #ifdef ENABLE_THREAD_SAFETY
+ 	pthread_mutex_unlock(&ssl_config_mutex);
+ #endif
  }
  
  /*
