【问题标题】:MYSQL C ConnectorMYSQL C 连接器
【发布时间】:2011-12-05 01:39:13
【问题描述】:

我有一个 C 进程正在快速写入 mysql 数据库 ~ 每秒 10 次。此过程使用 MySql C 连接器。

运行大约 2 分钟后,进程挂起并在系统监视器中显示

 "futex_wait_queue_me"

,还有

"Can't initialized threads: error 11" 

打印到控制台,我假设由 C 连接器库(因为我不打印这个)。在写入之后,与 mysql 的连接失败并显示

"MySQL server has gone away".

这可能是什么原因造成的?我只写 1 个线程。

fyi,我正在使用该库。将来会有互斥锁和解锁,因为我将对日志记录进行多线程处理。实际应用中的日志记录事件会少得多,但我试图在这个特定的测试中尽可能地强调它。

//pseudocode:
while(1)
    mutexlock
    connect();
    mysql_query();
    disconnect();
    sleep(100ms);
    mutexunlock


A better solution, maybe not the best
    connect();
    while(1)
        mutexlock

        if error on mysql_query();
            disconnect();
            connect();
        sleep(100ms);
        mutexunlock



//connect/disconnect functions
int DBConnector::connect()
{
    if(DBConnector::m_isConnected) return 0;//already connected...
    if(!mutexInitialized)
    {
        pthread_mutex_init(&DBLock, 0);
    }
    if(mysql_library_init(0, NULL, NULL))
    {
        LoggingUtil::logError("DBConnector.DB_connect [DB library init error] " + string(mysql_error(&DBConnector::m_SQLHandle)));
        DBConnector::m_isConnected = false;
        return -1;
    }

    if((mysql_init(&m_SQLHandle)) == NULL)
    {      
        LoggingUtil::logError("DBConnector.DB_connect [DB mysql init error] " + string(mysql_error(&DBConnector::m_SQLHandle)));
        DBConnector::m_isConnected = false;
        return -1;
    }

   if((mysql_real_connect(&DBConnector::m_SQLHandle, host.c_str(), user.c_str(), pw.c_str(), db.c_str(), port, socket.c_str(), client_flags)) == NULL)
   {
       LoggingUtil::logError("DBConnector.DB_connect [DB Connect error] " + string(mysql_error(&DBConnector::m_SQLHandle)));
       DBConnector::m_isConnected = false;
       return -1;
   }   

    DBConnector::m_isConnected = true;
    return 0;
}
int DBConnector::disconnect()
{
    DBConnector::m_isConnected = false;
    mysql_close(&DBConnector::m_SQLHandle);

    mysql_library_end();
    return 0;
}

【问题讨论】:

  • mysql 自己处理比赛和其他相同问题时,为什么你使用mutex

标签: mysql c linux


【解决方案1】:

尽量不打电话

mysql_library_init(0, NULL, NULL);

mysql_library_end();

在每次连接尝试时。

此外,您的第二个想法是在每次 mysql-access 时不重新连接要好得多,因为建立连接总是需要一些时间/资源。对你来说一无所有。

查询失败后,无需重新连接数据库。

【讨论】:

  • mysql 连接一段时间后超时,所以我只是在出错时重新连接。
猜你喜欢
  • 2015-02-03
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
  • 1970-01-01
  • 2023-03-12
  • 2011-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多