Thread safety


Thread safety

Thread safety is a computer programming 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 programmer but since the late 1990s has become a commonplace issue. In a multi-threaded program, several threads execute simultaneously in a shared address space. Every thread has access to virtually all the memory 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. Thread safety is a property aimed at minimizing surprising behavior 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 variables or the heap
*allocating/reallocating/freeing resources that have global limits (files, sub-processes, etc.)
*indirect accesses through handles or pointers
*any "visible side-effect" (e.g., access to volatile variables in the C programming language)

A subroutine is reentrant, and thus thread-safe, if it only uses variables from the stack, depends only on the arguments 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 information in variables local to each task, usually on its stack, instead of in static or global variables.; Mutual exclusion : 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 conditions, deadlocks, livelocks, starvation, and various other ills enumerated in many operating systems textbooks.; 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 reentrant.; Atomic operations : Shared data are 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 are always kept in a valid state, no matter what other threads access it. Atomic operations 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 atomically update the shared data from the private copy. Thus, most of the code is concurrent, and little time is spent serialized.

ee also

*Control flow analysis
*Priority inversion
*Concurrency control
*Exception safety
*Communicating sequential processes - a technique for analyzing concurrency
*Re-Entrant Read-Write Lock

External links

* [http://wiki.tcl.tk/3839 Thread-safe Tcl Extensions] (wiki page)
*Article " [http://javalobby.org/articles/thread-safe/index.jsp Thread-safe webapps using Spring] " by Steven Devijver
* [http://www.javaworld.com/javaworld/javaqa/1999-04/01-threadsafe.html Thread-safe design]
*Article " [http://www.javaworld.com/javaworld/jw-08-1998/jw-08-techniques.html Design for thread safety] " by Bill Venners
*Article " [http://www.javaworld.com/javaworld/jw-07-2004/jw-0712-threadsafe.html Write thread-safe servlets] " by Phillip Bridgham
*Article " [http://jelovic.com/articles/smart_pointer_thread_safety.htm Smart Pointer Thread Safety] " by Dejan Jelovic
* [http://www.thinkingparallel.com/2006/10/15/a-short-guide-to-mastering-thread-safety/ A Short Guide to Mastering Thread-Safety]


Wikimedia Foundation. 2010.

Look at other dictionaries:

  • Thread-Safety — Saltar a navegación, búsqueda Thread safety (Seguridad en hilos) es un concepto de programación de computadores aplicable en el contexto de los programas multi threaded. Una pieza de código es thread safe si funciona correctamente durante la… …   Wikipedia Español

  • Thread-safety — Потоковая безопасность (англ. thread safety) это концепция программирования, применимая к многопоточным программам. Код потоково безопасный, если он функционирует корректно при использовании из нескольких потоков одновременно. В частности,… …   Википедия

  • Thread (computer science) — This article is about the concurrency concept. For the multithreading in hardware, see Multithreading (computer architecture). For the form of code consisting entirely of subroutine calls, see Threaded code. For other uses, see Thread… …   Wikipedia

  • Thread pool pattern — In the thread pool pattern in programming, a number of threads are created to perform a number of tasks, which are usually organized in a queue. Typically, there are many more tasks than threads. As soon as a thread completes its task, it will… …   Wikipedia

  • Thread-Sicherheit — Threadsicherheit (engl. thread safety) ist eine Eigenschaft von Softwarekomponenten und hat eine wichtige Bedeutung in der Softwareentwicklung. Sie besagt, dass eine Komponente gleichzeitig von verschiedenen Programmbereichen mehrfach ausgeführt… …   Deutsch Wikipedia

  • Thread-safe — Threadsicherheit (engl. thread safety) ist eine Eigenschaft von Softwarekomponenten und hat eine wichtige Bedeutung in der Softwareentwicklung. Sie besagt, dass eine Komponente gleichzeitig von verschiedenen Programmbereichen mehrfach ausgeführt… …   Deutsch Wikipedia

  • Safety wire — Safety wiring of two pairs of drilled head bolts Safety wire or lockwire is common in the aircraft and racing industries as an extra precaution to keep vital fasteners from unintentionally loosening and parts from falling off due to vibration or… …   Wikipedia

  • Safety — (Roget s Thesaurus) < N PARAG:Safety >N GRP: N 1 Sgm: N 1 safety safety security surety impregnability Sgm: N 1 invulnerability invulnerability invulnerableness &c.???adj. Sgm: N 1 danger past danger past danger over Sgm …   English dictionary for students

  • thread — thread1 [θred] n ▬▬▬▬▬▬▬ 1¦(for sewing)¦ 2¦(ideas)¦ 3 pick up the thread(s) 4¦(internet)¦ 5¦(line)¦ 6¦(on a screw)¦ 7 threads ▬▬▬▬▬▬▬ [: Old English; Origin: thrAd] 1.) ¦(FOR SEWING)¦ …   Dictionary of contemporary English

  • thread — 1 noun 1 COTTON/SILK ETC (C, U) a long thin string of cotton, silk etc used to sew or weave cloth: Have you got a needle and thread? 2 IDEAS (singular) the connection between the different parts of an explanation, story etc: a common thread… …   Longman dictionary of contemporary English