Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Thread safety
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Concept in multi-threaded computer programming}} In [[multi-threaded]] [[computer programming]], a function is '''thread-safe''' when it can be invoked or accessed concurrently by multiple threads without causing unexpected behavior, [[race condition]]s, or data corruption.<ref>{{cite book |last=Kerrisk |first=Michael |title=The Linux Programing Interface |publisher=[[No Starch Press]] |year=2010 |page=699 |postscript=, "Chapter 31: THREADS: THREAD SAFETY AND PER-THREAD STORAGE"}}</ref><ref name=":1" /> As in the multi-threaded context where a program executes several threads simultaneously in a shared [[address space]] and each of those threads has access to every other thread's [[computer storage|memory]], thread-safe functions need to ensure that all those threads behave properly and fulfill their design specifications without unintended interaction.<ref name=":0">{{Cite web |publisher=[[Oracle Corporation|Oracle]] |first= |date=November 2020 |title=Multithreaded Programming Guide: Chapter 7 Safe and Unsafe Interfaces |url=https://docs.oracle.com/cd/E37838_01/html/E61057/compat-14994.html#scrolltoc |access-date=2024-04-30 |website=Docs Oracle |postscript=; "Thread Safety"}}</ref> There are various strategies for making thread-safe data structures.<ref name=":0" /> ==Levels of thread safety== Different vendors use slightly different terminology for thread-safety,<ref>{{cite web|url=https://www.ibm.com/docs/en/i/7.5?topic=safety-api-thread-classifications |title=API thread safety classifications |publisher=IBM |date=2023-04-11 |access-date=2023-10-09}}</ref> but the most commonly used thread-safety terminology are:<ref name=":1">{{cite web |last=Oracle |date=2010-11-01 |title=Oracle: Thread safety |url=https://docs.oracle.com/cd/E37838_01/html/E61057/compat-14994.html#scrolltoc |access-date=2013-10-16 |publisher=Docs.oracle.com |postscript="A procedure is thread safe when the procedure is logically correct when executed simultaneously by several threads"; "3 level of thread-safe"}}</ref> *'''Not thread safe''': Data structures should not be accessed simultaneously by different threads. *'''Thread safe, serialization''': Uses '''a single mutex for all resources''' to guarantee the thread to be free of [[race condition#Computing|race conditions]] when those resources are accessed by multiple threads simultaneously. *'''Thread safe, MT-safe''': Uses '''a mutex for every single resource''' to guarantee the thread to be free of [[race condition#Computing|race conditions]] when those resources are accessed by multiple threads simultaneously. Thread safety guarantees usually also include design steps to prevent or limit the risk of different forms of [[deadlock (computer science)|deadlock]]s, as well as optimizations to maximize concurrent performance. However, deadlock-free guarantees cannot always be given, since deadlocks can be caused by [[callback (computer programming)|callbacks]] and violation of [[architectural layer]]ing independent of the library itself. [[Library (computing)|Software libraries]] can provide certain thread-safety guarantees.<ref>{{Cite web |title=MT Safety Levels for Libraries |url=https://docs.oracle.com/cd/E37838_01/html/E61057/compat-89113.html#scrolltoc |access-date=2024-05-17 |website=Docs Oracle}}</ref> For example, concurrent reads might be guaranteed to be thread-safe, but concurrent writes might not be. Whether a program using such a library is thread-safe depends on whether it uses the library in a manner consistent with those guarantees. ==Implementation approaches== Listed are two classes of approaches for avoiding [[race condition#Computing|race conditions]] to achieve thread-safety. The first class of approaches focuses on avoiding shared state and includes: ; [[Reentrant (subroutine)|Re-entrancy]]<ref>{{cite web |title=Reentrancy and Thread-Safety | Qt 5.6 |url=https://doc.qt.io/qt-5/threads-reentrancy.html |access-date=2016-04-20 |publisher=Qt Project}}</ref>: Writing code in such a way that it can be partially executed by a thread, executed by the same thread, or simultaneously executed by another thread and still correctly complete the original execution. This requires the saving of [[state (computer science)|state]] information in variables local to each execution, usually on a stack, instead of in [[static variable|static]] or [[global variable|global]] variables or other non-local state. All non-local states must be accessed through atomic operations and the data-structures must also be reentrant. ; [[Thread-local storage]]: Variables are localized so that each thread has its own private copy. These variables retain their values across [[subroutine]]s and other code boundaries and are thread-safe since they are local to each thread, even though the code which accesses them might be executed simultaneously by another thread. ; [[Immutable object]]s: The state of an object cannot be changed after construction. This implies both that only read-only data is shared and that inherent thread safety is attained. Mutable (non-const) operations can then be implemented in such a way that they create new objects instead of modifying the existing ones. This approach is characteristic of [[functional programming]] and is also used by the ''string'' implementations in Java, C#, and Python. (See [[Immutable object]].) The second class of approaches are synchronization-related, and are used in situations where shared state cannot be avoided: ;[[Mutual exclusion]]: Access to shared data is ''serialized'' using mechanisms that ensure only one thread reads or writes to the shared data at any time. Incorporation of mutual exclusion needs to be well thought out, since improper usage can lead to side-effects like [[deadlock (computer science)|deadlock]]s, [[livelock]]s, and [[resource starvation]]. ; [[Linearizability|Atomic operations]]: Shared data is accessed by using atomic operations which cannot be interrupted by other threads. This usually requires using special [[machine language]] instructions, which might be available in a [[runtime library]]. Since the operations are atomic, the shared data is always kept in a valid state, no matter how other threads access it. Atomic operations form the basis of many thread locking mechanisms, and are used to implement mutual exclusion primitives. ==Examples== In the following piece of [[Java (programming language)|Java]] code, the Java keyword [[list of Java keywords#synchronized|synchronized]] makes the method thread-safe: <syntaxhighlight lang="java"> class Counter { private int i = 0; public synchronized void inc() { i++; } } </syntaxhighlight> In the [[C (programming language)|C programming language]], each thread has its own stack. However, a [[static variable]] is not kept on the stack; all threads share simultaneous access to it. If multiple threads overlap while running the same function, it is possible that a static variable might be changed by one thread while another is midway through checking it. This difficult-to-diagnose [[logic error]], which may compile and run properly most of the time, is called a [[race condition#Software|race condition]]. One common way to avoid this is to use another shared variable as a [[lock (computer science)|"lock" or "mutex"]] (from '''mut'''ual '''ex'''clusion). In the following piece of C code, the function is thread-safe, but not reentrant: <span class="anchor" id="mutexexample"></span> <syntaxhighlight lang="c"> # include <pthread.h> int increment_counter () { static int counter = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // only allow one thread to increment at a time pthread_mutex_lock(&mutex); ++counter; // store value before any other threads increment it further int result = counter; pthread_mutex_unlock(&mutex); return result; } </syntaxhighlight> In the above, <code>increment_counter</code> can be called by different threads without any problem since a mutex is used to synchronize all access to the shared <code>counter</code> variable. But if the function is used in a reentrant interrupt handler and a second interrupt arises while the mutex is locked, the second routine will hang forever. As interrupt servicing can disable other interrupts, the whole system could suffer. The same function can be implemented to be both thread-safe and reentrant using the lock-free [[linearizability|atomics]] in [[C++11]]: <syntaxhighlight lang="cpp"> # include <atomic> int increment_counter () { static std::atomic<int> counter(0); // increment is guaranteed to be done atomically int result = ++counter; return result; } </syntaxhighlight> ==See also== *[[Concurrency control]] *[[Concurrent data structure]] *[[Exception safety]] *[[Priority inversion]] *[[ThreadSafe]] ==References== {{Reflist}} ==External links== *{{cite web|url=https://www.javaworld.com/article/2077373/thread-safe-design-4-20-99.html|title=Thread-safe design (4/20/99)|author=Java Q&A Experts|date=20 April 1999|website=JavaWorld.com|access-date=2012-01-22}} *{{cite web|url=http://www.tutorialsdesk.com/2014/09/synchronization-and-thread-safety.html |title=Synchronization and Thread Safety Tutorial with Examples in Java|author=TutorialsDesk|date=30 Sep 2014|website=TutorialsDesk.com|access-date=2012-01-22}} *{{cite news|url=https://www.javaworld.com/article/2076747/design-for-thread-safety.html|title=Design for thread safety|last=Venners|first=Bill|date=1 August 1998|work=JavaWorld.com|access-date=2012-01-22}} *{{cite web|url=http://www.thinkingparallel.com/2006/10/15/a-short-guide-to-mastering-thread-safety/|title=A Short Guide to Mastering Thread-Safety|last=Suess|first=Michael|date=15 October 2006|website=Thinking Parallel|access-date=2012-01-22}} [[Category:Threads (computing)]] [[Category:Programming language topics]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Cite book
(
edit
)
Template:Cite news
(
edit
)
Template:Cite web
(
edit
)
Template:Reflist
(
edit
)
Template:Short description
(
edit
)