Home > other >  What is the correct way to connect to a MariaDB/MySQL server in a long running multithreaded C progr
What is the correct way to connect to a MariaDB/MySQL server in a long running multithreaded C progr

Time:09-27

After reading the docs it's still unclear to me what the correct usage is. Should one:

  1. Call mysql_init() and mysql_real_connect() once at startup, before thread creation, and all threads share the MYSQL handle returned from mysql_real_connect().
  2. Call mysql_init() once at startup, before thread creation, and then each thread calls mysql_real_connect() to get a thread specific MYSQL handle.
  3. Each thread calls mysql_init() and mysql_real_connect().
  4. Something else?

CodePudding user response:

  1. Sharing a connection over multiple threads is not a good idea, since you have to handle all kind of problems in your application: Transaction safety, protocol buffers etc.

  2. mysql_init() API function initializes a connection handle (MYSQL) which will be used to connect to a server via mysql_real_connect(). Trying to connect with the same handle again will result in an error (CR_ALREADY_CONNECTED=2058).

  3. Using one connection per thread is the better solution. If threads don't use the connection all the time, use a connection pool (e.g. by using Connector/C ).

  • Related