BUG #18312: libpq: PQsetdbLogin() not thread-safe

From: PG Bug reporting form <noreply(at)postgresql(dot)org>
To: pgsql-bugs(at)lists(dot)postgresql(dot)org
Cc: c(dot)maurer(at)gmx(dot)at
Subject: BUG #18312: libpq: PQsetdbLogin() not thread-safe
Date: 2024-01-26 10:06:48
Message-ID: 18312-bbbabc8113592b78@postgresql.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

The following bug has been logged on the website:

Bug reference: 18312
Logged by: Christian Maurer
Email address: c(dot)maurer(at)gmx(dot)at
PostgreSQL version: 16.1
Operating system: Windows 10 Pro
Description:

Hi

When calling PQsetdbLogin() concurrently the program crashes with RC=3.

Server: PostgreSQL 16.1 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 11.4.1
20230605 (Red Hat 11.4.1-2), 64-bit
libpq: postgresql-16.1-1-windows-x64-binaries.zip (coming from
https://www.enterprisedb.com/download-postgresql-binaries)

Output:
PQisthreadsafe: 1
Connect 0
Connect 2
Connect 1
Connect 3
Connected 0
Connected 2
Finished 0
Finished 2
=> 'End' was not reached
=> %ERRORLEVEL% is 3
=> Thread 1 and 3 did not connect/finish

When calling PQsetdbLogin() and PQfinish() once before the multi-threading
starts, there is no crash and we get the expected output:
PQisthreadsafe: 1
Connect 0
Connect 2
Connect 3
Connect 1
Connected 3
Finished 3
Connected 1
Finished 1
Connected 2
Connected 0
Finished 2
Finished 0
End

Regards
Christian

-- main.cpp start --
#include <iostream>
#include <thread>
#include <vector>
#include <pgsql/libpq-fe.h>

void test(int i)
{
try {
std::cout << "Connect " << i << std::endl;
PGconn *pgConn = PQsetdbLogin("myHost", (const char*)NULL, (const
char*)NULL, (const char*)NULL, "myDatabase", "myUser", "myPassword");
std::cout << "Connected " << i << std::endl;
PQfinish(pgConn);
std::cout << "Finished " << i << std::endl;
}
catch (...)
{
std::cout << "Exception occurred in " << i << std::endl;
}
}

int main()
{
try {
std::cout << "PQisthreadsafe: " << PQisthreadsafe() << std::endl;

//PGconn* pgConn = PQsetdbLogin("myHost", (const char*)NULL, (const
char*)NULL, (const char*)NULL, "myDatabase", "myUser", "myPassword");
//PQfinish(pgConn);

const std::size_t maxThreads = 4U;
std::vector<std::thread> myThreads;
for (std::size_t i = 0; i < maxThreads; ++i)
myThreads.push_back(std::thread(test, i));

for (std::thread& myThread : myThreads)
myThread.join();

std::cout << "End" << std::endl;
}
catch (...)
{
std::cout << "Exception occurred in main" << std::endl;
}

return 0;
}
-- main.cpp end --

Responses

Browse pgsql-bugs by date

  From Date Subject
Next Message Laurenz Albe 2024-01-26 10:54:52 Re: BUG #18295: In PostgreSQL a unique index on targeted columns is sufficient to support a foreign key
Previous Message Michael Paquier 2024-01-26 09:22:41 Re: Fwd: BUG #18016: REINDEX TABLE failure