尝试从多个线程连接时出现MariaDB C++连接器错误

e0bqpujr  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(121)

在ubuntu 20.04上使用MariaDB C++ Connector和gcc编译器。在对一个web服务器应用程序进行负载测试时,发现只要有多个并发连接,服务器就会崩溃。这被缩小到mariadb驱动程序的connect成员。报告的错误通常是以下两个错误之一:

terminate called after throwing an instance of 'std::logic_error'
  what():  basic_string::_M_construct null not valid
Aborted (core dumped)

terminate called after throwing an instance of 'std::invalid_argument'
  what():  stoi
Aborted (core dumped)

由于发布服务器的源代码是不可行的,因此我复制了一个最小的工作示例,它只使用标准库和mariadb/conncpp.hpp


# include <mariadb/conncpp.hpp>

# include <iostream>

# include <thread>

# include <string>

sql::Driver* driver = sql::mariadb::get_driver_instance();
sql::SQLString connectionUrl = "jdbc:mariadb://localhost:3306/the_database_name";
sql::Properties properties = {{"user", "the_username"}, {"password", "the_password"}};

int main()
{
    // simulate 2 concurrent connections each making 500 requests
    std::vector<std::function<void()>> t1cbs;
    std::vector<std::function<void()>> t2cbs;
    for(int i = 0; i < 500; i++) // if does not fail for you at 500 up the number until it does
    {
        t1cbs.push_back([&]{
            std::unique_ptr<sql::Connection> conn(driver->connect(connectionUrl, properties));
            std::cout << "t1:" << conn->getHostname().c_str() << std::endl;
        });

        // comment out this block to keep the second thread from executing, and you will see 
        // that no errors occur
        t2cbs.push_back([&]{
            std::unique_ptr<sql::Connection> conn(driver->connect(connectionUrl, properties));
            std::cout << "t2:" << conn->getHostname().c_str() << std::endl;
        });
    }

    std::thread t1([&]{
        for(auto& cb : t1cbs)
            cb();
    });

    std::thread t2([&]{
        for(auto& cb : t2cbs)
            cb();
    });

    t1.join();
    t2.join();

    return 0;
}

好奇是否有什么我没有看到的东西,其他人可能会指出?虽然在阅读了文档后,它似乎很直接...唯一的问题可能是在driver->connect中发生了一些线程不安全的事情?不确定...很困惑...任何想法都非常感谢!

编辑经过进一步研究,我发现了以下示例,其中提到如果您有多个线程,则可能会出现问题......但仍在尝试找出如何规避此问题。

相关问题