Concurrence in PHP

Surely you’ve ever met in PHP concurrency issues. Think about it for a moment, I’m sure you have many cases, and there is no easy solution in PHP language in order to protect critical code.

Imagine an API to manage a balance of points with a request that makes this tasks:

  • Read the current balance from the database
  • Calculations
  • Write the new result in the database

As this API can launch multiple asynchronous requests, we can have some problems like some of the operations could be overwritten with the result of another.

I will show you two ways to solved this problem:

The flock() function of PHP

With this feature you can lock and unlock the access to a file. We just need to pass a file handler and the operation we want to do:

  • LOCK_SH to get a shared lock (reader).
  • LOCK_EX to get an exclusive lock (writer).
  • LOCK_UN to release the lock (shared or exclusive).

For example:

What we are doing is checking if the file is locked. If it is free, then flock() locks the file, and we can do the operations safely. At the end we unlock the file so that another process can take the lock.

While the file is locked other processes are queued waiting for the lock release.

You can add an additional option that will prevent the process from waiting when a file lock is requested. This means that if the lock file is not available, flock() returns a false value, instead of waiting for release.

 

The library “malkusch/lock

A few months ago I found this fantastic library that solves this problem very well and is very easy to use. Thank you for your work Markus Malkusch.

Here you can see an example:

This method ensures that the code is executed by only one process at the same time. Other processes must wait until it is available. The critical code can throw an exception, which would release the lock too.

It also offers several implementations to manage locks

The library is well documented. I encourage you to see how it works and find out all the options that offers.

I hope this information will be useful for you. See you soon 🙂