MySQL 8.0 Reference Manual Including MySQL NDB Cluster 8.0

28.7.3.3 Writing C API Threaded Client Programs

This section provides guidance for writing client programs that use the thread-related functions in the MySQL C API. For further information about these functions, see Section 28.7.15, “C API Threaded Function Descriptions”. For examples of source code that uses them, look in the client directory of a MySQL source distribution:

As an alternative to thread programming, applications may find the asynchronous (nonblocking) C API functions useful. These functions enable applications to submit multiple outstanding requests to the server and determine when each has finished using polling. For more information, see Section 28.7.11, “C API Asynchronous Interface”.

If undefined-reference errors occur when linking a threaded program against the MySQL client library, the most likely cause is that you did not include the thread libraries on the link/compile command.

The client library is almost thread-safe. The biggest problem is that the subroutines in sql/net_serv.cc that read from sockets are not interrupt-safe. This was done with the thought that you might want to have your own alarm that can break a long read to a server. If you install interrupt handlers for the SIGPIPE interrupt, socket handling should be thread-safe.

To avoid aborting the program when a connection terminates, MySQL blocks SIGPIPE on the first call to mysql_library_init(), mysql_init(), or mysql_connect(). To use your own SIGPIPE handler, first call mysql_library_init(), then install your handler.

The client library is thread-safe per connection. Two threads can share the same connection with the following caveats:

If a thread does not create the connection to the MySQL database but calls MySQL functions, take the following into account:

When you call mysql_init(), MySQL creates a thread-specific variable for the thread that is used by the debug library (among other things). If you call a MySQL function before the thread has called mysql_init(), the thread does not have the necessary thread-specific variables in place and you are likely to end up with a core dump sooner or later. To avoid problems, you must do the following:

  1. Call mysql_library_init() before any other MySQL functions. It is not thread-safe, so call it before threads are created, or protect the call with a mutex.

  2. Arrange for mysql_thread_init() to be called early in the thread handler before calling any MySQL function. (If you call mysql_init(), it calls mysql_thread_init() for you.)

  3. In the thread, call mysql_thread_end() before calling pthread_exit(). This frees the memory used by MySQL thread-specific variables.

The preceding notes regarding mysql_init() also apply to mysql_connect(), which calls mysql_init().