BUG #18312: libpq: PQsetdbLogin() not thread-safe - Mailing list pgsql-bugs

From PG Bug reporting form
Subject BUG #18312: libpq: PQsetdbLogin() not thread-safe
Date
Msg-id 18312-bbbabc8113592b78@postgresql.org
Whole thread Raw
Responses Aw: BUG #18312: libpq: PQsetdbLogin() not thread-safe
List pgsql-bugs
The following bug has been logged on the website:

Bug reference:      18312
Logged by:          Christian Maurer
Email address:      c.maurer@gmx.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 --


pgsql-bugs by date:

Previous
From: Michael Paquier
Date:
Subject: Re: Fwd: BUG #18016: REINDEX TABLE failure
Next
From: Laurenz Albe
Date:
Subject: Re: BUG #18295: In PostgreSQL a unique index on targeted columns is sufficient to support a foreign key