5

I'm working on a plugin. I've created an API that reads and writes to a custom table in the DB. This API can be called potentially from N clients simultaneously (and it really happens). I noticed that in this case problems arise. To give a specific example:

if (is_null($wpdb->get_var("SELECT column FROM my_table_name WHERE condition"))) {
    // branch 1
}
else {
    // branch 2
}

In the branch 1 I innocently assume that the variable obtained from the DB is NULL, but maybe this is no longer true because it has been changed by another thread. I need the guarantee that, at least until the end of branch 1, this condition has not changed.

What's the WordPress-way to solve this problem? Semaphores, file locking, MySQL LOCK TABLE? Or there are better solutions? I searched for a long time on the web, but I wasn't able to find anything definitive. How does WordPress itself do (or the main plugins) in a case like this?

  • 1
    It doesn't. :( I remember hearing some chatter about this, but essentially this is untypical and underdeveloped issue in WP. – Rarst Mar 11 '15 at 20:34
  • So there are no solutions? But the WordPress core has to somehow support multithreading, otherwise how could manage concurrent requests? – User Mar 12 '15 at 7:53
  • 1
    Have a look at stackoverflow.com/questions/4710869/… – KenB Mar 12 '15 at 13:24
1

Is your plugin intended for use by others, or is it only going to be used on servers you control? If the latter, then there might be a few ways to achieve what you want. For instance, the Sync extension. With that, I think you could use a mutex or semaphore to set a flag, which you could then use in your read/write functions.

If you already have memcache available, then that might be a lightweight way to do the same thing, without needing to install a new extension.

Failing that, you might be able to use a db table lock, but that seems really heavy-handed, and I'd worry about the impact on database performance.

  • Thanks for your answer! The plugin is meant for distribution so it is not installed on my own servers. Then the only solution is the -awkward- MySQL TABLE LOCK? I'm shocked! – User Mar 12 '15 at 7:57
  • Well, you could set a flag in the options table, probably using a Transient. codex.wordpress.org/Transients_API – Dougal Campbell Mar 13 '15 at 18:24
  • I'm not sure I understand. Could you explain what you mean? – User Mar 15 '15 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.