thread confinement
thread confiment 是一种实践,确保只有一个线程可以访问数据,这样的数据叫做thread-local数据,因为它是与某一特定的线程相关的。
thread-local数据是线程安全的,因为只有一个线程可以访问这些数据,这就消除了竞争的风险。由于竞争不存在,因此不需要对数据进行加锁,因此thread confinement这个实践可以使得你的代码更加安全(从源头上大大降低了编码错误的隐患)且扩展性更好(无锁)。
大部分编程语言没有强制保证thread confinment的机制,它是一个高层次的编程范式,而不是语言或者操作系统的特性。诸如thread local storage (TLS)这种功能使得thread confinement变得更加容易,但是程序员依然需要努力确保数据的引用不要从拥有这些数据的线程中逃逸出去。
Thread confinement is the practice of ensuring that data is only accessible from one thread. Such data is called thread-local as it is local, or specific, to a single thread.
Thread-local data is thread-safe, as only one thread can get at the data, which eliminates the risk of races. And because races are nonexistent, thread-local data doesn't need locking. Thus thread confinement is a practice that makes your code safer (by eliminating a huge source of programming error) and more scalable (by eliminating locking).
Most languages don't have mechanisms to enforce thread confinement; it is a higher-level programming pattern and not a language or OS feature. Functionality such as thread local storage (TLS) makes thread confinement easier, but the programmer must still work to ensure references to the data does not escape the owning thread.