什么是线程安全?

来源:互联网 发布:java swing怎么运行 编辑:程序博客网 时间:2024/05/16 16:24

Wiki about Thead Safe: http://en.wikipedia.org/wiki/Thread_safety

引用Wikipedia:

Thread safety is a computer programming concept applicable in the context ofmulti-threaded programs. A piece of code is thread-safe if it onlymanipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time. There are various strategies for making thread-safe data structures.

线程安全,首先是适应于多线程环境下的。
线程安全最本质的要求即,多线程访问共享数据时不会产生某种出乎意料的冲突的情况。

线程安全是个比较宽的概念,其下有对应的几点特性或实现方法

引自Wikipedia

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.
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 mutal 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 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 how other threads access it. Atomic operations form the basis of many thread locking mechanisms, and are used to implement mutual exclusion primitives.

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 used by the string implementations in Java, C# and Python.

以上英文解释的比较清楚了,我大概梳理一下我的理解
Re-entrance(重入):代码被线程部分执行(线程切换),在下次同一线程回来继续执行剩余代码时,各部分的状态(比如使用到的变量)保持与之前不变,这就是可重入的其中一个概念。因为线程切换的时候,其他线程的执行可能修改了一些东西,比如全局变量(可以说,使用了全局变量的代码极易成为线程不安全的)
Mutual exclusion(互斥):顺序化的地访问共享数据,即在一个线程访问结束前,其他线程不能访问,一般使用互斥锁来实现。但是要小心使用不当产生死锁等情况
Immutable objects:不会修改原有对象,而是产生一个新的对象


0 0