【问题标题】:MySQL cppconn threads segmentation faultMySQL cppconn 线程分段错误
【发布时间】:2013-10-21 07:33:55
【问题描述】:

我目前正在开发一个使用数据库连接的小型 C++ 程序。 它是通过 CPPCONN 连接器与 MySQL 数据库的连接。

原因

我正在使用多个线程,因此我创建了以下方法:

void Database::startThread()
{
    fDriver->threadInit();
}

void Database::stopThread()
{
    fDriver->threadEnd();
}

void Database::connect(const string & host, const string & user, const string & password, const string & database)
{
        fDriver = sql::mysql::get_driver_instance();
        fConnection.reset(fDriver->connect((SQLString)host,(SQLString)user,(SQLString)password));
        fConnection->setSchema((SQLString) database);
        fStatement.reset(fConnection->createStatement());
        fConnection->setClientOption("multi-queries","true");
        fConnection->setClientOption("multi-statements","true");
}

问题是我在调用 fDriver->threadInit() 时遇到了分段错误。 我可以向你保证,fDriver 在那个时候通过 connect 函数被正确地实例化了。 (fDriver 也不为空)

崩溃

很遗憾,我无法提供更多有用的信息,但这是 GDB 的回溯:

Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7ffff4d66700 (LWP 16786)]
0x0000000000414547 in Database::startThread (this=Unhandled dwarf expression opcode 0xf3
#0  0x0000000000414547 in Database::startThread (this=Unhandled dwarf expression opcode 0xf3) at src/core/database.cpp:73
#1  0x0000000000405443 in Parser::Parser (this=0x7ffff4d659b8) at src/core/sv_parse.cpp:11
#2  0x000000000041e76d in MessageProcessor::MessageProcessor (this=0x7ffff4d659b0, serverStartTime=...) at src/server/messageProcessor.cpp:12
#3  0x000000000041bae8 in Server::__lambda1::operator() (__closure=0x62c740) at src/server/server.cpp:89
#4  0x00007ffff763f550 in execute_native_thread_routine () at ../../../../../libstdc++-v3/src/c++11/thread.cc:84
#5  0x00007ffff6edb851 in start_thread () from /lib64/libpthread.so.0
#6  0x00007ffff6c2994d in clone () from /lib64/libc.so.6

备注

现在奇怪的部分:这种崩溃并非一直发生! 有时它工作得很好。 但是,如果没有,那当然是非常烦人的。 CPPCONN 版本是 1.1.3,我们使用的是 g++ 版本 4.8.1。

希望有人能解开这个谜团!

吉里尔

【问题讨论】:

    标签: c++ mysql multithreading segmentation-fault


    【解决方案1】:

    我为同样神秘的分段错误苦苦挣扎了好几个小时。 我发现在 get_driver_instance() 周围添加互斥锁可以解决问题。 这是线程函数的基本框架。这适用于从数据库中选择,可能不适用于插入或更新。

    #include <mutex>
    
    std::mutex mtx;
    
    void test() 
    {
      sql::Driver *driver;
      sql::Connection *con;
    
      try {  
        mtx.lock();
        driver = get_driver_instance();
        mtx.unlock();
        driver->threadInit();
        con = driver->connect(HOST, USER, PASS);
        ...
        con->close();
        driver->threadEnd();
      } catch(...) { ... }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-02-29
      • 2022-01-10
      • 1970-01-01
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      • 2018-04-25
      • 2016-02-09
      • 1970-01-01
      相关资源
      最近更新 更多