=== modified file 'driver/handle.c' --- driver/handle.c 2010-08-19 15:37:55 +0000 +++ driver/handle.c 2010-10-26 07:32:44 +0000 @@ -43,6 +43,13 @@ #include "driver.h" +#ifdef _UNIX_ +/* variables for thread counter */ +static pthread_key_t myodbc_thread_counter_key; +static int myodbc_thread_key_inited= 0; +#endif + + /* @type : myodbc3 internal @purpose : to allocate the environment handle and to maintain @@ -52,7 +59,14 @@ SQLRETURN SQL_API my_SQLAllocEnv(SQLHENV FAR *phenv) { #ifdef _UNIX_ - myodbc_init(); /* This is done in LibMain on XP so it probably needs to be in this func only when in UNIX - PAH */ + /* Initialize just once upon allocating the environment */ + if(myodbc_thread_key_inited == 0) + { + /* Init thread key just once for all threads */ + myodbc_thread_key_inited= 1; + pthread_key_create (&myodbc_thread_counter_key, 0); + } + myodbc_init(); #endif #ifndef _UNIX_ @@ -160,6 +174,26 @@ DBC FAR *dbc; ENV FAR *penv= (ENV FAR*) henv; +#ifdef _UNIX_ + long *thread_count; + thread_count= (long*)pthread_getspecific(myodbc_thread_counter_key); + + /* Increment or allocate the thread counter */ + if (thread_count) + { + ++(*thread_count); + } + else + { + thread_count= my_malloc(sizeof(long), MYF(0)); + (*thread_count)= 1; + pthread_setspecific(myodbc_thread_counter_key, thread_count); + + /* Call it just for safety */ + mysql_thread_init(); + } +#endif + if (mysql_get_client_version() < MIN_MYSQL_VERSION) { char buff[255]; @@ -269,6 +303,30 @@ GlobalFree(GlobalHandle((HGLOBAL) hdbc)); #else my_free((char*) hdbc,MYF(0)); + + { + long *thread_count; + thread_count= (long*)pthread_getspecific(myodbc_thread_counter_key); + + if (thread_count) + { + if (*thread_count) + { + (*thread_count)--; + } + + if (*thread_count == 0) + { + /* The value to the key must be reset before freeing the buffer */ + pthread_setspecific(myodbc_thread_counter_key, 0); + my_free(thread_count, MYF(0)); + + /* Last connection deallocated, supposedly the thread is finishing */ + mysql_thread_end(); + } + } + } + #endif return SQL_SUCCESS; }