In computer science, a non-blocking algorithm ensures that threads competing for a shared resource do not have their execution indefinitely postponed by mutual exclusion. That is, the suspension of one or more threads will not stop the potential progress of the remaining threads. Such algorithms are designed to avoid requiring a critical section. Often, they allow multiple processes to make progress on a problem without ever blocking each other. For some operations, these algorithms provide an alternative to locking mechanisms.
A non-blocking algorithm is lock-free if there is guaranteed system-wide progress regardless of scheduling; it iswait-free if there is also guaranteed per-thread progress. "Non-blocking" was used as a synonym for "lock-free" until around 2003. Since 2003, the term only excludes progress-blocking interactions with a preemptive scheduler.
The word "non-blocking" was traditionally used to describe telecommunications networks that could route a connection through a set of relays "without having to re-arrange existing calls", see Clos network. Also, if the telephone exchange "is not defective, it can always make the connection", see Nonblocking minimal spanning switch.
The traditional approach to multi-threaded programming is to use locks to synchronize access to shared resources. Synchronization primitives such as mutexes, semaphores, and critical sections are all mechanisms by which a programmer can ensure that certain sections of code do not execute concurrently, if doing so would corrupt shared memory structures. If one thread attempts to acquire a lock that is already held by another thread, the thread will block until the lock is free.
Blocking a thread is undesirable for many reasons. An obvious reason is that while the thread is blocked, it cannot accomplish anything. If the blocked thread was performing a high-priority or real-time task, it would be highly undesirable to halt its progress. Other problems are less obvious. Certain interactions between locks can lead to error conditions such as deadlock, livelock, and priority inversion. Using locks also involves a trade-off between coarse-grained locking, which can significantly reduce opportunities for parallelism, and fine-grained locking, which requires more careful design, increases locking overhead and is more prone to bugs.
Non-blocking algorithms are also safe for use in interrupt handlers: even though the preempted thread cannot be resumed, progress is still possible without it. In contrast, global data structures protected by mutual exclusion cannot safely be accessed in a handler, as the preempted thread may be the one holding the lock.
With few exceptions, non-blocking algorithms use atomic read-modify-write primitives that the hardware must provide, the most notable of which is compare and swap (CAS). Critical sections are almost always implemented using standard interfaces over these primitives. Until recently, all non-blocking algorithms had to be written "natively" with the underlying primitives to achieve acceptable performance. However, the emerging field of software transactional memory promises standard abstractions for writing efficient non-blocking code. 
Additionally, some non-blocking data structures are weak enough to be implemented without special atomic primitives. These exceptions include:
- single-reader single-writer ring buffer FIFO
- Read-copy-update with a single writer and any number of readers. (The readers are wait-free; the writer is usually lock-free, until it needs to reclaim memory).
- Read-copy-update with multiple writers and any number of readers. (The readers are wait-free; multiple writers generally serialize with a lock and are not obstruction-free).
Wait-freedom is the strongest non-blocking guarantee of progress, combining guaranteed system-wide throughput with starvation-freedom. An algorithm is wait-free if every operation has a bound on the number of steps the algorithm will take before the operation completes. This property is critical for real-time systems and is always nice to have as long as the performance cost is not too high.
It was shown in the 1980s that all algorithms can be implemented wait-free, and many transformations from serial code, called universal constructions, have been demonstrated. However, the resulting performance does not in general match even naïve blocking designs. Several papers have since improved the performance of universal constructions, but still, their performance is far below blocking designs.
Several papers have investigated the difficulty of creating wait-free algorithms. For example, it has been shown that the widely available atomic conditional primitives, CAS and LL/SC, cannot provide starvation-free implementations of many common data structures without memory costs growing linearly in the number of threads.
But in practice these lower bounds do not present a real barrier as spending a cache line or exclusive reservation granule (up to 2kb on ARM) of store per thread in the shared memory is not considered too costly for practical systems (typically the amount of store logically required is a word, but physically CAS operations on the same cache line will collide, and LL/SC operations in the same exclusive reservation granule will collide, so the amount of store physically required is greater).
Wait-free algorithms were rare until 2011, both in research and in practice. However, in 2011 Kogan and Petrank presented a wait-free queue building on the CAS primitive, generally available on common hardware. Their construction expands the lock-free queue of Michael and Scott, which is an efficient queue often used in practice. A follow-up paper by Kogan and Petrank provided a methodology for making wait-free algorithms fast and used this methodology to make the wait-free queue practically as fast as its lock-free counterpart.
Lock-freedom allows individual threads to starve but guarantees system-wide throughput. An algorithm is lock-free if it satisfies that when the program threads are run sufficiently long at least one of the threads makes progress (for some sensible definition of progress). All wait-free algorithms are lock-free.
In general, a lock-free algorithm can run in four phases: completing one's own operation, assisting an obstructing operation, aborting an obstructing operation, and waiting. Completing one's own operation is complicated by the possibility of concurrent assistance and abortion, but is invariably the fastest path to completion.
The decision about when to assist, abort or wait when an obstruction is met is the responsibility of a contention manager. This may be very simple (assist higher priority operations, abort lower priority ones), or may be more optimized to achieve better throughput, or lower the latency of prioritized operations.
Correct concurrent assistance is typically the most complex part of a lock-free algorithm, and often very costly to execute: not only does the assisting thread slow down, but thanks to the mechanics of shared memory, the thread being assisted will be slowed, too, if it is still running.
Obstruction-freedom is possibly the weakest natural non-blocking progress guarantee. An algorithm is obstruction-free if at any point, a single thread executed in isolation (i.e., with all obstructing threads suspended) for a bounded number of steps will complete its operation. All lock-free algorithms are obstruction-free.
Obstruction-freedom demands only that any partially completed operation can be aborted and the changes made rolled back. Dropping concurrent assistance can often result in much simpler algorithms that are easier to validate. Preventing the system from continually live-locking is the task of a contention manager.
Obstruction-freedom is also called optimistic concurrency control.
Some obstruction-free algorithms use a pair of "consistency markers" in the data structure. Processes reading the data structure first read one consistency marker, then read the relevant data into an internal buffer, then read the other marker, and then compare the markers. The data is consistent if the two markers are identical. Markers may be non-identical when the read is interrupted by another process updating the data structure. In such a case, the process discards the data in the internal buffer and tries again.
- Concurrent data structure
- ABA problem
- Concurrency control
- Communicating sequential processes
- Lock (software engineering)
- Memory barrier
- Mutual exclusion
- Pre-emptive multitasking
- Priority inversion
- Resource starvation
- Room synchronization
- Software transactional memory
- Partitioned global address space
- Herlihy, M.; Luchangco, V.; Moir, M. (2003). "Obstruction-Free Synchronization: Double-Ended Queues as an Example". 23rd International Conference on Distributed Computing Systems. p. 522.
- Harris, Tim; Fraser, Keir (26 November 2003). "Language support for lightweight transactions". ACM SIGPLAN Notices 38 (11): 388. doi:10.1145/949343.949340.
- Harris, Tim; Marlow, S.; Peyton-Jones, S.; Herlihy, M. (June 15–17). "Composable memory transactions". Proceedings of the 2005 ACM SIGPLAN Symposium on Principles and Practice of Parallel Programming, PPoPP '05 : Chicago, Illinois. New York, NY: ACM Press. pp. 48–60. ISBN 1-59593-080-9. Check date values in:
- libcds - C++ library of lock-free containers and safe memory reclamation schema
- liblfds - A library of lock-free data structures, written in C
- Concurrency Kit - A C library for non-blocking system design and implementation
- Herb Sutter. "Lock-Free Code: A False Sense of Security".
- Herb Sutter. "Writing Lock-Free Code: A Corrected Queue".
- Herb Sutter. "Writing a Generalized Concurrent Queue".
- Herb Sutter. "The Trouble With Locks".
- Herlihy, Maurice P. (August 15–17). "Impossibility and universality results for wait-free synchronization". Proceedings of the Seventh Annual ACM Symposium on Principles of Distributed Computing : Toronto, Ontario, Canada. New York, N.Y.: Association for Computing Machinery. pp. 276–290. ISBN 0-89791-277-2. Check date values in:
- Fich, Faith; Hendler, Danny; Shavit, Nir (July 25–28). "On the inherent weakness of conditional synchronization primitives". Proceedings of the 23rd Annual ACM Symposium on Principles of Distributed Computing, PODC 2004 : St. John's, Newfoundland, Canada. New York, NY: ACM Press. pp. 80–87. ISBN 1-58113-802-4. Check date values in:
- Kogan, Alex; Petrank, Erez (February 12–16). "Wait-free queues with multiple enqueuers and dequeuers". Proceedings of the 16th ACM SIGPLAN Symposium on Principles and Practice of Parallel Programming (PPOPP 2011). San Antonio, TX: ACM Press. pp. 223–234. ISBN 978-1-4503-0119-0. Check date values in:
- Michael, Maged; Scott, Michael (May 23–26). "Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms". Proceedings of the Fifteenth Annual ACM Symposium on Principles of Distributed Computing(PODC 1996). Philadelphia, Pennsylvania, USA: ACM Press. pp. 267–275. ISBN 0-89791-800-2. Check date values in:
- Kogan, Alex; Petrank, Erez (February 25–29). "A methodology for creating fast wait-free data structures". Proceedings of the 17ACM SIGPLAN Symposium on Principles and Practice of Parallel Programming (PPOPP 2012). New Orleans, LA: ACM Press. pp. 141–150. ISBN 978-1-4503-1160-1. Check date values in: