1

我有多个线程需要连接到 MySQL 服务器的单个实例。如果每个线程都创建并处理自己的连接,那么一切都会按预期进行。我想实现一个简单的连接池:

void query_user(MYSQL* conn) 
{
  mysql_thread_init();

  std::ostringstream query;
  query << "select * from user u where u.username = '" << "stack" << "'";

  if (mysql_query(conn, query.str().c_str())) {
    fprintf(stderr, "%s\n", mysql_error(conn));
    exit(-1);
  }

  MYSQL_RES* res = mysql_use_result(conn);

  MYSQL_ROW row;
  while ((row = mysql_fetch_row(res)) != NULL) {
    printf("%s %s %s %s %s %s %s %s %s\n", 
       row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8]);
  }

  mysql_free_result(res);

  mysql_thread_end();
 }

#define POOL_SIZE 2

int main(int argc, char** argv) 
{
  mysql_library_init(argc, argv, NULL); 

  // Create Connection pool

  MYSQL* connection_pool[POOL_SIZE];

  for (size_t i = 0; i < sizeof(connection_pool)/sizeof(MYSQL*); ++i) {
    connection_pool[i] = mysql_init(NULL);

    if (!mysql_real_connect(connection_pool[i], server,
                user, password, database, 0, NULL, 0)) {
      fprintf(stderr, "%s\n", mysql_error(connection_pool[i]));
      exit(-1);
    }
  }

  // Thread Pool
  pthread_t thread_pool[POOL_SIZE];

  for (size_t i = 0; i < sizeof(thread_pool)/sizeof(pthread_t); ++i) {
    pthread_create(&thread_pool[i], NULL, 
               reinterpret_cast<void* (*)(void*)>(query_user), 
           (void*)&connection_pool[i]);
  }

  // join threads
  for (size_t i = 0; i < sizeof(thread_pool)/sizeof(pthread_t); ++i) {
        pthread_join(thread_pool[i], NULL);
    mysql_close(connection_pool[i]);
  }

  mysql_library_end();

  return 0;
}

我在 mysql_real_query 中有一个总线错误

你能指出它有什么问题吗?连接池还有一些好处吗?

我正在链接 libmysqlclient_r 这应该是线程安全的

谢谢,

4

1 回答 1

2

我认为有问题:

(void*)&connection_pool[i]

恕我直言,应该是:

(void*)connection_pool[i]
于 2013-06-13T14:37:49.427 回答