Skip to content

Commit 95ac01b

Browse files
authored
Opt spin lock (alibaba#1126)
1 parent 2904fef commit 95ac01b

1 file changed

Lines changed: 12 additions & 3 deletions

File tree

thread/thread.h

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -214,13 +214,22 @@ namespace photon
214214
#endif
215215
}
216216

217+
inline void spin_wait_n(uint32_t n) {
218+
for (uint32_t i = 0; i < n; ++i) {
219+
spin_wait();
220+
}
221+
}
222+
217223
class spinlock {
218224
public:
219225
int lock() {
226+
uint32_t delay = 1;
227+
constexpr uint32_t max_delay = 1024;
220228
while (unlikely(xchg())) {
221-
while (likely(load())) {
222-
spin_wait();
223-
}
229+
do {
230+
spin_wait_n(delay);
231+
if (delay < max_delay) delay <<= 1;
232+
} while (likely(load()));
224233
}
225234
return 0;
226235
}

0 commit comments

Comments
 (0)