From 644b445428845a4e662c15059193dfa492bc0c44 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Wed, 24 Nov 2021 15:59:28 +0100 Subject: [PATCH 1/2] If the thread does not get the lock in the short term, yield the CPU Reduces the amount of wasted processor cycles --- library/std/src/sys/hermit/mutex.rs | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/library/std/src/sys/hermit/mutex.rs b/library/std/src/sys/hermit/mutex.rs index 691e7e07902d8..79692ef2442ca 100644 --- a/library/std/src/sys/hermit/mutex.rs +++ b/library/std/src/sys/hermit/mutex.rs @@ -46,8 +46,17 @@ impl Spinlock { #[inline] fn obtain_lock(&self) { let ticket = self.queue.fetch_add(1, Ordering::SeqCst) + 1; + let mut counter: u16 = 0; while self.dequeue.load(Ordering::SeqCst) != ticket { - hint::spin_loop(); + counter = counter + 1; + if counter < 100 { + hint::spin_loop(); + } else { + counter = 0; + unsafe { + abi::yield_now(); + } + } } } From 6911af9d06ef4f92659326ce426c6aefc7b47282 Mon Sep 17 00:00:00 2001 From: Stefan Lankes Date: Wed, 24 Nov 2021 21:12:56 +0100 Subject: [PATCH 2/2] Improving the readability Co-authored-by: kennytm --- library/std/src/sys/hermit/mutex.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/sys/hermit/mutex.rs b/library/std/src/sys/hermit/mutex.rs index 79692ef2442ca..415cbba101c67 100644 --- a/library/std/src/sys/hermit/mutex.rs +++ b/library/std/src/sys/hermit/mutex.rs @@ -48,7 +48,7 @@ impl Spinlock { let ticket = self.queue.fetch_add(1, Ordering::SeqCst) + 1; let mut counter: u16 = 0; while self.dequeue.load(Ordering::SeqCst) != ticket { - counter = counter + 1; + counter += 1; if counter < 100 { hint::spin_loop(); } else {