20.4.55 Comment rendre le client thread-safe

The client is ``almost'' thread-safe. The biggest problem is that the subroutines in `net.c' 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.

The standard client libraries are not compiled with the thread options.

To get a thread-safe client, use the -lmysys, -lstring and -ldbug libraries and net_serv.o that the server uses.

When using a threaded client, you can make great use of the routines in the `thr_alarm.c' file. If you are using routines from the mysys library, the only thing you must remember is to call my_init() first!

All functions except mysql_real_connect() are currently thread-safe. The following notes describe how to compile a thread-safe client library and use it in a thread-safe manner. (The notes below for mysql_real_connect() actually apply to mysql_connect() as well, but since mysql_connect() is deprecated, you should be using mysql_real_connect() anyway.)

To make mysql_real_connect() thread-safe, you must recompile the client library with this command:

shell> CPPFLAGS=-DTHREAD_SAFE_CLIENT ./configure ...

You may get some errors because of undefined symbols when linking the standard client, because the pthread libraries are not included by default.

The resulting `libmysqlclient.a' library is now thread-safe. What this means is that client code is thread-safe as long as two threads don't query the same connection handle returned by mysql_real_connect() at the same time; the client/server protocol allows only one request at a time on a given connection. If you want to use multiple threads on the same connection, you must have a mutex lock around your mysql_query() and mysql_store_result() call combination. Once mysql_store_result() is ready, the lock can be released and other threads may query the same connection. (In other words, different threads can use different MYSQL_RES pointers that were created with mysql_store_result(), as long as they use the proper locking protocol.) If you program with POSIX threads, you can use pthread_mutex_lock() and pthread_mutex_unlock() to establish and release a mutex lock.

If you used mysql_use_result() rather than mysql_store_result(), the lock would need to surround mysql_use_result() and the calls to mysql_fetch_row(). However, it really is best for threaded clients not to use mysql_use_result().