Download the PHP package hokoo/wp-lock without Composer
On this page you can find all versions of the php package hokoo/wp-lock. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download hokoo/wp-lock
More information about hokoo/wp-lock
Files in hokoo/wp-lock
Package wp-lock
Short Description A library for locking and mutexes for the WordPress Core
License MIT
Homepage https://github.com/hokoo/wp-lock
Informations about the package wp-lock
WP Lock
This was previously a fork from original repo soulseekah/wp-lock by Gennady Kovshenin. Now here is the standalone repo with such changes as:
- Custom database table is used as the WPDB locks' storage that allows to manage locks in simple and convenient way.
- Fast: making one lock takes up to one single query instead of 11 and more.
- Readable: the code is well documented and easy to understand.
WP Lock's Preconditions
Consider the following user balance topup function that is susceptible to a race condition:
Try to call the above code 100 times in 16 threads. The balance will be less than it is supposed to be.
The code below is thread safe.
Usage
Require via Composer composer require hokoo/wp-lock
in your plugin.
Don't forget to include the Composer autoloader in your plugin and declare using of the WP_Lock
class.
Acquire a read blocking lock without a timeout.
Lock levels
WP_Lock::READ
- other processes can acquire READ but not WRITE until the original lock is released. A shared read lock.WP_Lock::WRITE
(default) - other processes can't acquire READ or WRITE locks until the original lock is released. An exclusive read-write lock
Blocking policy
- Blocking means that the process will wait here until the lock is obtained (5 microseconds spinlock).
- Non-blocking lock acquisition does not wait for the other locks to be released, but returns false immediately if the lock is already acquired by another process. So, it should be checked for success.
Timeout policy
- 0-second timeout means that the lock should be released, otherwise it will be released automatically after the php process is finished.
- Non-zero timeout means that the lock might not be released manually, and then it will be done automatically after the specified number of seconds.
Lock Existence Check
You may also want to check if a lock is acquired by another process without actually trying to acquire it.
Caveats
In highly concurrent setups you may get Deadlock errors from MySQL. This is normal. The library handles these gracefully and retries the query as needed.