代码的并发执行是关于两件事,相互排斥和变化的可见性。相互排斥是关于管理对某些资源的争夺性更新。变化的可见性是指控制这些变化何时对其他线程可见。如果你能消除对争夺式更新的需求,就有可能避免对相互排斥的需求。如果你的算法能够保证任何给定的资源只被一个线程修改,那么相互排斥就没有必要了。读取和写入操作要求所有的改变都对其他线程可见。然而,只有争先恐后的写操作需要相互排斥的变化。
在任何并发环境中,最昂贵的操作是争夺性的写访问。要让多个线程写到同一个资源,需要复杂而昂贵的协调。通常,这是通过采用某种锁定策略来实现的。
Concurrent execution of code is about two things, mutual exclusion and visibility of change. Mutual exclusion is about managing contended updates to some resource. Visibility of change is about controlling when such changes are made visible to other threads. It is possible to avoid the need for mutual exclusion if you can eliminate the need for contended updates. If your algorithm can guarantee that any given resource is modified by only one thread, then mutual exclusion is unnecessary. Read and write operations require that all changes are made visible to other threads. However only contended write operations require the mutual exclusion of the changes.
The most costly operation in any concurrent environment is a contended write access. To have multiple threads write to the same resource requires complex and expensive coordination. Typically this is achieved by employing a locking strategy of some kind.