• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
WP Desk = premium plugins for WordPress & WooCommerce
  • Plugins
        • Checkout & OrdersMake your work easier and automate the orders. Adjust the order form to your needs and make it more useful to your customers. Print order labels directly from WooCommerce. Put the orders in order using our plugins. Find out how to streamline the procurement process in your store.
          • Flexible Checkout Fields
          • Active Payments
          • Automatic Payment Status
          • Flexible Refund and Return Order
          • Print Orders and Address Labels
          • Flexible Subscriptions Recurring Shipping
          • Flexible Subscriptions Payment Retry
          • Flexible Subscriptions Stock Management
        • ProductsThese plugins will help you manage your WooCommerce products. Here you will find the plugins to import and update products from XML or CSV files. Then you can change the product unit of measure, show the lowest price in the last 30 days (Omnibus Directive), or let customers name the product price!
          • Flexible Product Fields
          • Dropshipping Import Products
          • Dropshipping FTP Import Products
          • Dropshipping Export Products
          • Custom Price
          • WP Desk Omnibus
          • Flexible Quantity Calculator
          • Dropshipping Orders Export
        • MarketingPromote your store online. Add products from your shop to price comparison websites directly from WooCommerce. Acquire new customers and communicate with your existing ones. Build a customer base and communicate with clients using one of the most effective marketing tools, namely e-mail marketing. Check out our promotional tools!
          • Flexible Pricing
          • Flexible Wishlist - Analytics & Emails
          • OLX WooCommerce
          • Flexible PDF Coupons
          • ShopMagic
          • Flexible Invoices
  • Bundle🔥
  • WP Desk Care
  • Support
  • Blog
  • My Account
  • 0

More results

Mutexes, Deadlocks and other developer nightmares

Tech Posts, WordPress design & development

Krzysiek Dyszczyk3 minutes readUpdated: 2021-03-15Updated: 2026-06-08
blog category heading image

The use of atomic operations is a beautiful and simple solution to many problems that arise in multi-threaded environments where many processes attempt to modify the same data. Unfortunately, their use does not always solve the problem.

This entry is a continuation of atomic operations. If you don't know what these operations are like, read it first.

Contents

  • The atomic operation is not always enough
  • We don't always work with the database
  • Critical section
  • Mutex
  • Hungry and sad processes
  • Deadlocks
    • Related Articles
  • Atomic operations in WordPress
  • WooCommerce shortcodes & blocks - the complete list with examples

The atomic operation is not always enough

Imagine that you want to make an operation in a store that is dependent on stock. If we have exactly five products in stock, maybe we would like to send the warehouse admin an SMS informing them that the products are running out. Let's try to do this:

If two processes take the stock simultaneously, both can receive the number 5 and send an SMS. The first process will not update the store until the second process has read its state. The administrator will get two SMSs instead of one, even though the inventory reduction is atomic. Thankfully it was just an SMS, not a transfer of half a million dollars.
Regardless of how sending the SMS is done, we cannot easily combine it with modifying the database's inventory.

We don't always work with the database

WooCommerce also allows you to change the inventory using the API. Suppose that, as part of handling a customer request, we want to take the stock value of a certain product, reduce it by one and save it. If there may appear a situation where two clients send an API request and get stock value first and then save the modified one, one of the processes may overwrite the data with an incorrect value. Since we are using the API, we cannot convert both activities into one query.

Either of these two situations makes it impossible to solve the problem simply by converting to atomic operation.

When the result of an operation depends on processes execution order, it is called race conditions. The success of such an operation depends on luck; it is a bug that is very difficult to reproduce and fix.

Critical section

The crux of the problem we encounter lies in that more than one process can execute the same code in parallel. The solution to the problem is obvious: you need to protect the part of the code that cannot run parallelly. Subsequent processes should wait until the previous process finishes processing such code. The critical section is what we call a particular part of the code that can only be executed simultaneously by one process. But how to ensure that other processes wait for the colleague who first entered the section?

Mutex

The easiest way to ensure that subsequent processes do not start processing the critical section code is to use a shared flag between processes. "Shared" means that every process can read or modify its state. The first process that enters a section sets the flag via an atomic operation and thus notifies other processes that the section code is being processed at that point. When you leave a section, the flag is cleared so another process can enter the section. Such a flag is an example of a simple algorithm ensuring MUTual EXclusion or mutex: if one process is in the section, it precludes subsequent processes from entering the section.

Implementing a mutex is not spectacularly difficult, but it's mistake-prone. For this reason, it is easiest to use tools that others have created. A few years ago, at WP Desk, we needed mutexes, among others, due to the need to generate thread-resistant invoice numbering. Since we couldn't find an implementation that would work well for WordPress, we made ours, available at https://gitlab.com/wpdesk/wp-mutex

How to use a mutex? It is straightforward: Processes that encounter the acquireLock command will wait a maximum of 5 seconds for permission to enter the critical section. If access is still not possible after 5 seconds, an exception will be thrown. What happens if we forget to clear the flag?

Hungry and sad processes

If the process that sets the flag stays in the critical section for too long, the processes waiting for input will throw exceptions. They will be starving while waiting for resources.
An even worse situation may arise if a process encounters an error while parsing the code in a section. It may exit the section and not clear the flag, starving all other processes. For this reason, it's best to wrap the entire section in try/finally. As a result, even if there is an error while sending the SMS, the process will still remember to clear the flag and release the mutex.

Deadlocks

Sometimes we need more than one critical section, e.g. when the process in section B waits for permission to enter section A. This permission will never be granted because the process that processes section A is simultaneously waiting to enter section B. Processes will wait for each other, leading to a deadlock. In practice, deadlocks occur very rarely in the PHP code itself because the business tasks facing WordPress developers, and therefore the code we write, are pretty straightforward. However, we will come back to deadlocks in the future, especially in the context of MySQL InnoDB deadlock, which can cause neurosis even in the most stoical stoics.

Almost always, PHP processes are run multi-threaded. Therefore, the ability to synchronize processes is a knowledge that every programmer should have. Have I exhausted the topic of multithreading? No, this is just the beginning, but the information provided suffices to deal with most of the problems that await inattentive WordPress developers :)

Related Articles

Atomic operations in WordPress

As the famous saying goes, There are only two hard things in Computer Science: cache invalidation and naming things. The author of this saying has app...
WooCommerce shortcodes (practical guide with the cart, checkout, products, shop, product, and login shortcode examples)

WooCommerce shortcodes & blocks - the complete list with examples

You may find many posts about WooCommerce shortcodes online. In this article, you’ll find the full WooCommerce shortcode list with screenshots. Quickl...

3 minutes read3733 views

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Krzysiek Dyszczyk

Co‑founder & CEO of WP Desk

LinkedIn Profile

Krzysiek is the Co‑founder and CEO of WP Desk, having co-founded the company in 2012, and previously served as CTO, managing its technical vision...

Powered by WP Desk

WP Desk brings you great WooCommerce plugins. We strive to save your time and money by speeding up your processes. Use our plugins to build a better store. Awesome support included in the package.

Premium WooCommerce Plugins →
WP Desk › Blog › WordPress design & development › Mutexes, Deadlocks and other developer nightmares

Primary Sidebar

Contents

  • The atomic operation is not always enough
  • We don’t always work with the database
  • Critical section
  • Mutex
  • Hungry and sad processes
  • Deadlocks

All Plugins Bundle £99

28 plugins included! 1 Site for each plugin Regular updates and support Priority 1-on-1 Support 30-day money back guarantee

Add to cart or View Details
WP Desk
Plugins used by 239,859+ shops

Stay updated on our how-to articles

WP Desk news, WooCommerce tips, promo codes - right to your inbox.

By entering your e-mail, you agree to our Terms & Conditions and Privacy Policy.

By entering your e-mail, you agree to our Terms & Conditions and Privacy Policy.

Footer

WP Desk - WooCommerce Plugins

At WP Desk we create great WooCommerce plugins with awesome support. Save time and money with our e-commerce solutions. See how we can help you improve your e-store →

Secured by Comodo

WP Desk

  • About us
  • Giving Back
  • Blog
  • Get Support
  • Contact us

Products

  • Premium Plugins
  • WP Desk Care
  • Documentation
  • WooCommerce Invoices
  • Email Marketing
  • PDF Coupons

Legal

  • Terms & Conditions
  • Refund Policy
  • Support Policy
  • Privacy Policy

© 2026 WP Desk

We value your privacy

We use necessary cookies to make our site work. We'd also like to set additional cookies to understand site usage, enhance your browsing experience, and serve personalized ads or content. By clicking ‘Accept All,’ you consent to our use of additional cookies.

Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
View preferences
  • {title}
  • {title}
  • {title}