We're doing a small benchmark of MySQL where we want to see how it performs for our data.
Part of that test is to see how it works when multiple concurrent threads hammers the server with various queries.
The MySQL documentation (5.0) isn't really clear about multi threaded clients. I should point out that I do link against the thread safe library (libmysqlclient_r.so
)
I'm using prepared statements and do both read (SELECT) and write (UPDATE, INSERT, DELETE).
mysql_real_connect()
returns the original DB handle which I got when I called mysql_init()
)mysql_affected_rows
returns the correct value instead of colliding with other thread's calls (mutex/locks could work, but it feels wrong)As maintainer of a fairly large C application that makes MySQL calls from multiple threads, I can say I've had no problems with simply making a new connection in each thread. Some caveats that I've come across:
libmysqlclient_r
.mysql_library_init()
(once, from main()
). Read the docs about use in multithreaded environments to see why it's necessary.MYSQL
structure using mysql_init()
in each thread. This has the side effect of calling mysql_thread_init()
for you. mysql_real_connect()
as usual inside each thread, with its thread-specific MYSQL struct.mysql_thread_end()
at the end of each thread (and mysql_library_end()
at the end of main()
). It's good practice anyway.Basically, don't share MYSQL
structs or anything created specific to that struct (i.e. MYSQL_STMT
s) and it'll work as you expect.
This seems like less work than making a connection pool to me.