Thread safety








Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without unintended interaction. There are various strategies for making thread-safe data structures.[1][2]


A program may execute code in several threads simultaneously in a shared address space where each of those threads has access to virtually all of the memory of every other thread. Thread safety is a property that allows code to run in multithreaded environments by re-establishing some of the correspondences between the actual flow of control and the text of the program, by means of synchronization.




Contents






  • 1 Levels of thread safety


  • 2 Implementation approaches


  • 3 Examples


  • 4 See also


  • 5 References


  • 6 External links





Levels of thread safety


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.


Different vendors use slightly different terminology for thread-safety:[3][4][5][6]




  • Thread safe: Implementation is guaranteed to be free of race conditions when accessed by multiple threads simultaneously.


  • Conditionally safe: Different threads can access different objects simultaneously, and access to shared data is protected from race conditions.


  • Not thread safe: Data structures should not be accessed simultaneously by different threads.


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.



Implementation approaches


Below we discuss two 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, reexecuted 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 state 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 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 existing ones. This approach is characteristic of functional programming and is also used by the string implementations in Java, C# and Python.[7]


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 method is thread-safe:


class Counter {
private int i = 0;

public synchronized void inc() {
i++;
}
}

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, the function is thread-safe, but not reentrant:


# 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;
}

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 in C++11:


# include <atomic>

int increment_counter ()
{
static std::atomic<int> counter(0);

// increment is guaranteed to be done atomically
int result = ++counter;

return result;
}


See also




  • Concurrency control

  • Exception safety

  • Priority inversion

  • ThreadSafe



References





  1. ^ Kerrisk, Michael (2010). The Linux Programing Interface. No Starch Press. p. 655..mw-parser-output cite.citation{font-style:inherit}.mw-parser-output .citation q{quotes:"""""""'""'"}.mw-parser-output .citation .cs1-lock-free a{background:url("//upload.wikimedia.org/wikipedia/commons/thumb/6/65/Lock-green.svg/9px-Lock-green.svg.png")no-repeat;background-position:right .1em center}.mw-parser-output .citation .cs1-lock-limited a,.mw-parser-output .citation .cs1-lock-registration a{background:url("//upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Lock-gray-alt-2.svg/9px-Lock-gray-alt-2.svg.png")no-repeat;background-position:right .1em center}.mw-parser-output .citation .cs1-lock-subscription a{background:url("//upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Lock-red-alt-2.svg/9px-Lock-red-alt-2.svg.png")no-repeat;background-position:right .1em center}.mw-parser-output .cs1-subscription,.mw-parser-output .cs1-registration{color:#555}.mw-parser-output .cs1-subscription span,.mw-parser-output .cs1-registration span{border-bottom:1px dotted;cursor:help}.mw-parser-output .cs1-ws-icon a{background:url("//upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Wikisource-logo.svg/12px-Wikisource-logo.svg.png")no-repeat;background-position:right .1em center}.mw-parser-output code.cs1-code{color:inherit;background:inherit;border:inherit;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;font-size:100%}.mw-parser-output .cs1-visible-error{font-size:100%}.mw-parser-output .cs1-maint{display:none;color:#33aa33;margin-left:0.3em}.mw-parser-output .cs1-subscription,.mw-parser-output .cs1-registration,.mw-parser-output .cs1-format{font-size:95%}.mw-parser-output .cs1-kern-left,.mw-parser-output .cs1-kern-wl-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right,.mw-parser-output .cs1-kern-wl-right{padding-right:0.2em}


  2. ^ "Multithreaded Programming Guide". Oracle Corporation. November 2010. A procedure is thread safe when the procedure is logically correct when executed simultaneously by several threads.


  3. ^ "Reentrancy and Thread-Safety | Qt 5.6". Qt Project. Retrieved 2016-04-20.


  4. ^ "ip::tcp – 1.51.0". Boost.org. Retrieved 2013-10-16.


  5. ^ "API thread safety classifications". Publib.boulder.ibm.com. 1998-06-09. Retrieved 2013-10-16.


  6. ^ "MT Interface Safety Levels – Multithreaded Programming Guide". Docs.oracle.com. 2010-11-01. Retrieved 2013-10-16.


  7. ^ Immutable object




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 Safetey in Java (4/20/99)". 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.




這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()