Bug #79177 mysql_real_connect multithread datarace and conflicting access
Submitted: 8 Nov 2015 20:27 Modified: 10 Nov 2015 10:07
Reporter: А Б Email Updates:
Status: Verified Impact on me:
None 
Category:MySQL Server: C API (client library) Severity:S2 (Serious)
Version:6.1.6 OS:CentOS
Assigned to: CPU Architecture:Any
Tags: data race, multithread, thread, thread safe, valgrind

[8 Nov 2015 20:27] А Б
Description:
Useing mysql_real_connect simultaneously in diferent threads makes valgrind drd and helgrind tools reporting data races and conflicting accesses in functions:
mysql_set_character_set_with_default_collation
get_charset_number_internal
get_internal_charset

How to repeat:
#include <string>
#include <iostream>
#include <mysql.h>
#include <thread>
#include <mutex>

std::mutex _cout_mutex;

int main()
{
  const std::string host="host";
  const std::string db="database_name";
  const std::string user="user";
  const std::string pass="password";
  const unsigned int port=3306;
  const unsigned int threads_count=20;

  mysql_library_init(0, nullptr, nullptr);

  auto connect=[&]
    {
      MYSQL *conn = mysql_init(nullptr);
      if (conn == nullptr)
	{
	  std::lock_guard<std::mutex> lock(_cout_mutex);
	  std::cout<<"Can not creare connection"<<std::endl;
	  return;
	}
      
      if(nullptr!=mysql_real_connect (conn,
				      host.c_str(),
				      user.c_str(),
				      pass.c_str(),
				      db.c_str(),
				      port,
				      nullptr,
				      0))
	{
	  std::lock_guard<std::mutex> lock(_cout_mutex);
	  std::cout<<"Connected"<<std::endl;
	} 
      else
	{
	  std::lock_guard<std::mutex> lock(_cout_mutex);
	  std::cout<<"Connection error="<<mysql_error(conn)<<std::endl;
	}
      
    };

  for (unsigned i=0; i<=threads_count;i++)
    {
      std::thread t(connect);
      t.detach();
    }

  while(true);

  return 0;
}

valgrind --tool=drd  --xml=yes  --xml-file=./drd.xml ./executable_name
[9 Nov 2015 8:52] А Б
helgrind xml output

Attachment: helgrind.xml (text/xml), 128.44 KiB.

[9 Nov 2015 8:53] А Б
valgrind drd xml output

Attachment: drd.xml (text/xml), 230.85 KiB.

[9 Nov 2015 9:21] А Б
CMake repeat bug project

Attachment: mysql_race_test.tgz (application/x-gzip, text), 1.68 KiB.

[10 Nov 2015 10:07] Chiranjeevi Battula
Hello  А Б,

Thank you for the bug report and test case.
Verified this behavior as described.

Thanks,
Chiranjeevi.
[10 Nov 2015 10:08] Chiranjeevi Battula
Output file.

Attachment: 79177_mysql_race.out (application/octet-stream, text), 21.45 KiB.