All Topics  
Thread-safe

 

   Email Print
   Bookmark   Link






 

Thread-safe



 
 
Thread safety is a computer programming
Computer programming

Computer programming is the process of writing, testing, debugging/troubleshooting, and maintaining the source code of computer programs. This source code is written in a programming language....
 concept applicable in the context of multi-threaded programs. A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads. In particular, it must satisfy the need for multiple threads to access the same shared data, and the need for a shared piece of data to be accessed by only one thread at any given time.

Thread safety is a key challenge in multi-threaded programming.






Discussion
Ask a question about 'Thread-safe'
Start a new discussion about 'Thread-safe'
Answer questions from other users
Full Discussion Forum



Encyclopedia


Thread safety is a computer programming
Computer programming

Computer programming is the process of writing, testing, debugging/troubleshooting, and maintaining the source code of computer programs. This source code is written in a programming language....
 concept applicable in the context of multi-threaded programs. A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads. In particular, it must satisfy the need for multiple threads to access the same shared data, and the need for a shared piece of data to be accessed by only one thread at any given time.

Thread safety is a key challenge in multi-threaded programming. It was once only a concern of the operating system
Operating system

An operating system is an interface between hardware and applications; it is responsible for the management and coordination of activities and the sharing of the limited resources of the computer....
 programmer
Programmer

A programmer is someone who writes computer software. The term computer programmer can refer to a specialist in one area of computer programming or to a generalist who writes code for many kinds of software....
 but since the late 1990s has become a commonplace issue. In a multi-threaded program, several threads execute simultaneously in a shared address space
Address space

In computing, an address space defines a range of discrete addresses, each of which may correspond to a physical or virtual memory register, a Node , peripheral device, disk sector or other logical or physical entity....
. Every thread has access to virtually all the memory
Computer storage

Computer data storage, often called storage or memory, refers to computer components, devices, and recording medium that retain digital data used for computing for some interval of time....
 of every other thread. Thus the flow of control and the sequence of accesses to data often have little relation to what would be reasonably expected by looking at the text of the program, violating the principle of least astonishment
Principle of least astonishment

In user interface design, programming language design, and ergonomics, the principle of least astonishment states that, when two elements of an interface conflict, or are ambiguous, the behaviour should be that which will least surprise the human User or programmer at the time the conflict arises....
. Thread safety is a property aimed at minimizing surprising behavior
Behavior

Behavior or behaviour refers to the action s or reactions of an object or organism, usually in Relational theory to the environment. Behavior can be conscious or Unconscious mind, overt or covert, and voluntary or involuntary....
 by re-establishing some of the correspondences between the actual flow of control and the text of the program.

Identification

It is not easy to determine if a piece of code is thread-safe or not. However, there are several indicators that suggest the need for careful examination to see if it is unsafe:
  • accessing global variable
    Global variable

    In computer programming, a global variable is a variable that is accessible in every scope . Interaction mechanisms with global variables are called global environment mechanisms....
    s or the heap
    Dynamic memory allocation

    In computer science, dynamic memory allocation is the allocation of computer storage storage for use in a computer program during the runtime of that program....
  • allocating/reallocating/freeing resources
    Resource (computer science)

    A resource, or system resource, is any physical or virtual component of limited availability within a computer system. Every device connected to a computer system is a resource....
     that have global limits (file
    Computer file

    A computer file is a block of arbitrary information, or resource for storing information, which is available to a computer program and is usually based on some kind of durable computer storage....
    s, sub-processes
    Process (computing)

    In computing, a process is an Object of a computer program that is being sequentially executed by a computer system that has the ability to run several computer programs Concurrency ....
    , etc.)
  • indirect accesses through handles or pointers
  • any visible side-effect (e.g., access to volatile variable
    Volatile variable

    In computer programming, particularly in the C and C++ programming languages, a variable or Object declared with the volatile keyword may be modified externally from the declaring object....
    s in the C programming language
    C (programming language)

    C is a general-purpose computer programming language originally developed in 1972 by Dennis Ritchie at the Bell Telephone Laboratories to implement the Unix operating system....
    )


A subroutine
Subroutine

In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code....
 is reentrant, and thus thread-safe, if it only uses variables from the stack
Stack (data structure)

In computer science, a stack is an abstract data type and data structure based on the principle of LIFO . Stacks are used extensively at every level of a modern computer system....
, depends only on the argument
Parameter (computer science)

In computer programming, a parameter is a special kind of variable#In_computer_programming that refers to data that a subroutine receives to operate on....
s passed in, and only calls other subroutines with similar properties. This is sometimes called a "pure function", and is much like a mathematical function.

Implementation

There are a few ways to achieve thread safety: Re-entrancy : Writing code in such a way that it can be partially executed by one task, reentered by another task, and then resumed from the original task. This requires the saving of state
State (computer science)

In computer science and automata theory, a state is a unique configuration of information in a program or machine. It is a concept that occasionally extends into some forms of systems programming such as Lexical analysiss and parsers....
 information in variables local to each task, usually on its stack, instead of in static
Static variable

In computer programming, the data value of a static variable persists for the life of the running process. Typically, a static variable has a broader Scope than other variables....
 or global
Global variable

In computer programming, a global variable is a variable that is accessible in every scope . Interaction mechanisms with global variables are called global environment mechanisms....
 variables. Mutual exclusion
Mutual exclusion

Mutual exclusion algorithms are used in concurrent programming to avoid the simultaneous use of a common resource, such as a global variable, by pieces of computer code called critical sections....
 : Access to shared data is serialized using mechanisms that ensure only one thread reads or writes the shared data at any time. Great care is required if a piece of code accesses multiple shared pieces of data—problems include race condition
Race condition

A race condition or race hazard is a flaw in a system or process whereby the output and/or result of the process is unexpectedly and critically dependent on the sequence or timing of other events....
s, deadlock
Deadlock

A deadlock is a situation wherein two or more competing actions are waiting for the other to finish, and thus neither ever does. It is often seen in a paradox like 'the chicken or the egg'....
s, livelocks, starvation
Resource starvation

In computer science, starvation is a computer multitasking-related problem, where a computer process is perpetually denied necessary Resource s....
, and various other ills enumerated in many operating system
Operating system

An operating system is an interface between hardware and applications; it is responsible for the management and coordination of activities and the sharing of the limited resources of the computer....
s textbooks. Thread-local storage
Thread-local storage

Thread-local storage is a computer programming method that uses static or global Computer storage local to a Thread .This is sometimes needed because all threads in a Process share the same address space....
 : Variables are localized so that each thread has its own private copy. These variables retain their values across subroutine
Subroutine

In computer science, a subroutine or subprogram is a portion of computer code within a larger computer program, which performs a specific task and is relatively independent of the remaining code....
 and other code boundaries, and are thread-safe since they are local to each thread, even though the code which accesses them might be reentrant. Atomic operations
Linearizability

In concurrent programming, an operation is atomic, or linearizable, if it appears to take effect instantaneously. Implementation details may be ignored by the user, except insofar as they affect performance....
 : Shared data are accessed by using atomic operations
Atomicity

In database systems, atomicity is one of the ACID database transaction properties. In an atomic transaction, a series of database operations either all occur, or nothing occurs....
 which cannot be interrupted by other threads. This usually requires using special machine language instructions, which might be available in a runtime library
Runtime library

In computer programming, a runtime library is a special program library used by a compiler, to implement functions built into a programming language, during the runtime of a computer program....
. Since the operations are atomic, the shared data are always kept in a valid state, no matter what other threads access it. Atomic operations
Linearizability

In concurrent programming, an operation is atomic, or linearizable, if it appears to take effect instantaneously. Implementation details may be ignored by the user, except insofar as they affect performance....
 form the basis of many thread locking mechanisms. One approach to making data thread-safe that combines several of the above elements is to make changes to a private copy of the shared data and then atomic
Atomic operation

An atomic operation in computer science refers to a set of Instruction s that can be combined so that they appear to the rest of the system to be a single operation with only two possible outcomes: success or failure....
ally update the shared data from the private copy. Thus, most of the code is concurrent
Concurrency (computer science)

In computer science, concurrency is a property of systems in which several computations are executing simultaneously, and potentially interacting with each other....
, and little time is spent serialized
Serialization

In computer science, in the context of data storage and transmission, serialization is the process of converting an object into a sequence of bits so that it can be stored on a storage medium or transmitted across a computer network connection link....
.

See also

  • Control flow analysis
  • Priority inversion
    Priority inversion

    In scheduling , priority inversion is the scenario where a low priority task holds a shared resource that is required by a high priority task. This causes the execution of the high priority task to be blocked until the low priority task has released the resource, effectively "inverting" the relative priorities of the two tasks....
  • Concurrency control
    Concurrency control

    In computer science, especially in the fields of computer programming , operating systems , multiprocessors, and databases, concurrency control ensures that correct results for concurrent operations are generated, while getting those results as quickly as possible....
  • Exception safety
    Exception handling

    Exception handling is a programming language construct or computer hardware mechanism designed to handle the occurrence of exceptions - special conditions that change the normal flow of execution....
  • Communicating sequential processes
    Communicating sequential processes

    In computer science, Communicating Sequential Processes is a specification language for describing patterns of interaction in concurrent systems....
     - a technique for analyzing concurrency
  • Re-Entrant Read-Write Lock


External links

  • (wiki page)
  • Article "" by Steven Devijver
  • Article "" by Bill Venners
  • Article "" by Phillip Bridgham
  • Article "" by Dejan Jelovic