Skip to content

Commit 4d04b0b

Browse files
committed
Remove wrong advice about spin locks from spin_loop_hint docs
Using a pure spin lock for a critical section in a preemptable thread is always wrong, however short the critical section may be. The thread might be preempted, which will cause all other threads to hammer busily at the core for the whole quant. Moreover, if threads have different priorities, this might lead to a priority inversion problem and a deadlock. More generally, a spinlock is not more efficient than a well-written mutex, which typically does several spin iterations at the start anyway. The advise about UP vs SMP is also irrelevant in the context of preemptive threads.
1 parent 0ec3706 commit 4d04b0b

File tree

1 file changed

+2
-10
lines changed

1 file changed

+2
-10
lines changed

src/libcore/sync/atomic.rs

+2-10
Original file line numberDiff line numberDiff line change
@@ -134,16 +134,8 @@ use crate::hint::spin_loop;
134134
/// This function is different from [`std::thread::yield_now`] which directly yields to the
135135
/// system's scheduler, whereas `spin_loop_hint` does not interact with the operating system.
136136
///
137-
/// Spin locks can be very efficient for short lock durations because they do not involve context
138-
/// switches or interaction with the operating system. For long lock durations they become wasteful
139-
/// however because they use CPU cycles for the entire lock duration, and using a
140-
/// [`std::sync::Mutex`] is likely the better approach. If actively spinning for a long time is
141-
/// required, e.g. because code polls a non-blocking API, calling [`std::thread::yield_now`]
142-
/// or [`std::thread::sleep`] may be the best option.
143-
///
144-
/// **Note**: Spin locks are based on the underlying assumption that another thread will release
145-
/// the lock 'soon'. In order for this to work, that other thread must run on a different CPU or
146-
/// core (at least potentially). Spin locks do not work efficiently on single CPU / core platforms.
137+
/// If actively spinning for a long time is required, e.g. because code polls a non-blocking API,
138+
/// calling [`std::thread::yield_now`] or [`std::thread::sleep`] may be the best option.
147139
///
148140
/// **Note**: On platforms that do not support receiving spin-loop hints this function does not
149141
/// do anything at all.

0 commit comments

Comments
 (0)