ArticleslgStudy

computer science

Thread safety

Thread safety is a computer science topic covered in the lgStudy science library. This page brings together a partial reference excerpt, illustrations, worked examples, real-world applications and a short study plan, so you can understand Thread safety rather than just read about it. In short: 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 conditions, or data corruption. 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 memory, thread-safe functions need…

Key takeaways

  • Thread safety belongs to computer science; place it in that map before memorising details.
  • Learn the definition first, then one example that makes the definition concrete.
  • Connect Thread safety to a quantity you can measure, compute or draw — that is where exam questions come from.
  • Reproduce the core statement of Thread safety from memory before moving on to harder problems.

Reference excerpt

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 conditions, or data corruption. 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 memory, thread-safe functions need to ensure that all those threads behave properly and fulfill their design specifications without unintended interaction. There are various strategies for making thread-safe data structures.

Levels of thread safety Different vendors use slightly different terminology for thread-safety, but the most commonly used thread-safety terminology are:

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 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 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 deadlocks, as well as optimizations to maximize concurrent performance. However, deadlock-free guarantees cannot always be given, since deadlocks can be caused by callbacks and violation of architectural layering independent of the library itself. Software libraries can provide certain thread-safety guarantees. 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 conditions to achieve thread-safety. The first class of approaches focuses on avoiding shared state and includes:

Re-entrancy 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 information in variables local to each execution, usually on a stack, instead of in static or 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 subroutines 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 objects 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 deadlocks, livelocks, and resource starvation. 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 code, the Java keyword synchronized makes the method thread-safe:

In the 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. One common way to avoid this is to use another shared variable as a "lock" or "mutex" (from mutual exclusion). In the following piece of C code which calls POSIX headers, the function is thread-safe, but not reentrant:

In the above, increment_counter can be called by different threads without any problem since a mutex is used to synchronize all access to the shared counter 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 atomics, which were introduced in C++11:

See also Concurrency control Concurrent data structure Exception safety Priority inversion ThreadSafe

References

External links Java Q&A Experts (20 April 1999). "Thread-safe design (4/20/99)". JavaWorld.com. Retrieved 2012-01-22. TutorialsDesk (30 Sep 2014). "Synchronization and Thread Safety Tutorial with Examples in Java". TutorialsDesk.com. Retrieved 2012-01-22. Venners, Bill (1 August 1998). "Design for thread safety". JavaWorld.com. Retrieved 2012-01-22. Suess, Michael (15 October 2006). "A Short Guide to Mastering Thread-Safety". Thinking Parallel. Retrieved 2012-01-22.

Worked examples

Example 1 — a first encounter with Thread safety

Start with the simplest possible case. Write down what Thread safety claims or describes in one sentence, then invent the smallest concrete situation in which that sentence is true. In computer science, the smallest case is usually a single object, a single equation or a single measurement. Check that every symbol or term in your sentence has a meaning in that case.

Example 2 — changing one variable

Take the situation from Example 1 and change exactly one quantity: double it, halve it, or set it to zero. Predict what should happen to Thread safety before you calculate. Comparing your prediction with the result is the fastest way to find out whether you understand the idea or only the words.

Example 3 — an exam-style question

Typical questions about Thread safety ask you to (a) state it precisely, (b) apply it to given data, and (c) explain a limitation. Practise writing all three answers in under five minutes; the third part is what separates a full-mark answer from an average one.

Applications of Thread safety

In research
Thread safety appears in computer science research whenever the underlying quantities have to be modelled precisely. Papers usually cite it as a starting assumption and then explore where it breaks down.
In technology and industry
Engineering practice reuses Thread safety in design rules, simulations and safety margins. Knowing the idea lets you read a specification sheet and understand why the numbers look the way they do.
In the classroom
Thread safety is common in secondary-school and first-year university syllabi. It links to neighbouring topics Programming language topics, Threads (computing), so understanding it makes those chapters shorter.
In everyday life
Look for Thread safety outside the textbook — in sport, cooking, traffic, electronics or the sky above you. An example you found yourself is remembered far longer than one you were given.
Ask Teacher Smith questions about this articleOpens your AI tutor with a question about “Thread safety” →

How to study Thread safety in 20 minutes

  1. Read the reference excerpt below once, without taking notes.
  2. Close the page and write down what Thread safety means in your own words.
  3. Compare your version with the excerpt and mark what you missed.
  4. Work through the three examples above with pen and paper.
  5. Explain Thread safety out loud to somebody else — or to Teacher Smith in the lgStudy chat.

Frequently asked questions

What is Thread safety in simple terms?

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 conditions, or data corruption. As in the multi-threaded context where a program executes several threads simultaneously in…

Why does Thread safety matter?

Because it connects several computer science ideas at once: it gives you a definition you can apply, a quantity you can calculate, and a way to check whether a result is plausible.

How should I study Thread safety?

Read the excerpt, restate it from memory, then work through the examples and applications listed on this page. The five-step study plan above takes about twenty minutes.

What does this page cover?

It gives you a compact reference excerpt plus original lgStudy explanations, examples, applications and study material on Thread safety.

Tags

  • Programming language topics
  • Threads (computing)

Keep exploring