Skip to content

Commit 842e6ce

Browse files
committed
fix race condition in atexit callbacks for connection canceling
1 parent b4933f6 commit 842e6ce

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

src/checkdb.c

+1
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,7 @@ check_indexes(void *arg)
292292
int i;
293293
check_indexes_arg *arguments = (check_indexes_arg *) arg;
294294
int n_indexes = 0;
295+
my_thread_num = arguments->thread_num;
295296

296297
if (arguments->index_list)
297298
n_indexes = parray_num(arguments->index_list);

src/utils/pgut.c

+12-1
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ bool interrupted = false;
3535
bool in_cleanup = false;
3636
bool in_password = false;
3737

38+
/* critical section when adding disconnect callbackups */
39+
static pthread_mutex_t atexit_callback_disconnect_mutex = PTHREAD_MUTEX_INITIALIZER;
40+
3841
/* Connection routines */
3942
static void init_cancel_handler(void);
4043
static void on_before_exec(PGconn *conn, PGcancel *thread_cancel_conn);
@@ -48,6 +51,7 @@ static void pgut_pgfnames_cleanup(char **filenames);
4851

4952
void discard_response(PGconn *conn);
5053

54+
/* Note that atexit handlers always called on the main thread */
5155
void
5256
pgut_init(void)
5357
{
@@ -237,7 +241,9 @@ pgut_connect(const char *host, const char *port,
237241

238242
if (PQstatus(conn) == CONNECTION_OK)
239243
{
244+
pthread_lock(&atexit_callback_disconnect_mutex);
240245
pgut_atexit_push(pgut_disconnect_callback, conn);
246+
pthread_mutex_unlock(&atexit_callback_disconnect_mutex);
241247
return conn;
242248
}
243249

@@ -365,7 +371,10 @@ pgut_disconnect(PGconn *conn)
365371
{
366372
if (conn)
367373
PQfinish(conn);
374+
375+
pthread_lock(&atexit_callback_disconnect_mutex);
368376
pgut_atexit_pop(pgut_disconnect_callback, conn);
377+
pthread_mutex_unlock(&atexit_callback_disconnect_mutex);
369378
}
370379

371380

@@ -840,7 +849,9 @@ call_atexit_callbacks(bool fatal)
840849
{
841850
pgut_atexit_item *item;
842851
pgut_atexit_item *next;
843-
for (item = pgut_atexit_stack; item; item = next){
852+
853+
for (item = pgut_atexit_stack; item; item = next)
854+
{
844855
next = item->next;
845856
item->callback(fatal, item->userdata);
846857
}

0 commit comments

Comments
 (0)