1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// SPDX-License-Identifier: MIT OR Apache-2.0
use super::Instant;
use super::{Condvar, WaitTimeoutResult};
use crate::Guard;
#[cfg(target_arch = "wasm32")]
use super::atomics_wait_supported;
impl Condvar {
/// Automatically chooses the right waiting strategy for your platform.
///
/// This is the recommended method as it papers over all platform differences:
/// - **Native**: Uses efficient thread parking
/// - **WASM with `Atomics.wait`**: Uses `Atomics.wait` for proper blocking
/// - **WASM without `Atomics.wait`**: Falls back to spinning (e.g., browser main thread)
///
/// You don't need to worry about "cannot block on main thread" errors -
/// this method handles that automatically by detecting the environment
/// and choosing the appropriate strategy.
///
/// # Spurious Wakeups
///
/// This method may return spuriously (without a notification). Always use it
/// in a loop that checks the condition.
///
/// # Examples
///
/// ```
/// # // std::thread::spawn panics on wasm32
/// # if cfg!(target_arch = "wasm32") { return; }
/// use wasm_safe_mutex::{Mutex, condvar::Condvar};
/// use std::sync::Arc;
/// # #[cfg(target_arch = "wasm32")]
/// use web_time::{Duration, Instant};
/// # #[cfg(not(target_arch = "wasm32"))]
/// # use std::time::{Duration, Instant};
/// # use std::thread;
///
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
/// let pair_clone = Arc::clone(&pair);
///
/// thread::spawn(move || {
/// let (mutex, condvar) = &*pair_clone;
/// let mut ready = mutex.lock_sync();
/// *ready = true;
/// drop(ready);
/// condvar.notify_one();
/// });
///
/// let (mutex, condvar) = &*pair;
/// let mut ready = mutex.lock_sync();
/// let deadline = Instant::now() + Duration::from_secs(1);
/// while !*ready {
/// let result;
/// (ready, result) = condvar.wait_sync_timeout(ready, deadline);
/// if result.timed_out() {
/// break;
/// }
/// }
/// assert!(*ready);
/// ```
pub fn wait_sync_timeout<'a, T>(
&self,
guard: Guard<'a, T>,
deadline: Instant,
) -> (Guard<'a, T>, WaitTimeoutResult) {
#[cfg(not(target_arch = "wasm32"))]
{
self.wait_block_timeout(guard, deadline)
}
#[cfg(target_arch = "wasm32")]
{
if atomics_wait_supported() {
self.wait_block_timeout(guard, deadline)
} else {
// Fallback to spin lock if Atomics.wait is not supported
self.wait_spin_timeout(guard, deadline)
}
}
}
/// Automatically waits while the predicate is `true`, bounded by the deadline,
/// choosing the best strategy per platform.
///
/// This is the recommended method as it papers over all platform differences:
/// - **Native**: Uses efficient thread parking
/// - **WASM with `Atomics.wait`**: Uses `Atomics.wait` for proper blocking
/// - **WASM without `Atomics.wait`**: Falls back to spinning (e.g., browser main thread)
///
/// # Examples
///
/// ```
/// # // std::thread::spawn panics on wasm32
/// # if cfg!(target_arch = "wasm32") { return; }
/// use wasm_safe_mutex::{Mutex, condvar::Condvar};
/// use std::sync::Arc;
/// # #[cfg(target_arch = "wasm32")]
/// use web_time::{Duration, Instant};
/// # #[cfg(not(target_arch = "wasm32"))]
/// # use std::time::{Duration, Instant};
/// # use std::thread;
///
/// let pair = Arc::new((Mutex::new(0), Condvar::new()));
/// let pair_clone = Arc::clone(&pair);
///
/// thread::spawn(move || {
/// let (mutex, condvar) = &*pair_clone;
/// let mut value = mutex.lock_sync();
/// *value = 10;
/// drop(value);
/// condvar.notify_one();
/// });
///
/// let (mutex, condvar) = &*pair;
/// let guard = mutex.lock_sync();
/// let deadline = Instant::now() + Duration::from_secs(1);
/// let (guard, result) = condvar.wait_sync_timeout_while(guard, deadline, |v| *v < 10);
/// if !result.timed_out() {
/// assert_eq!(*guard, 10);
/// }
/// ```
pub fn wait_sync_timeout_while<'a, T, F>(
&self,
guard: Guard<'a, T>,
deadline: Instant,
condition: F,
) -> (Guard<'a, T>, WaitTimeoutResult)
where
F: FnMut(&mut T) -> bool,
{
#[cfg(not(target_arch = "wasm32"))]
{
self.wait_block_timeout_while(guard, deadline, condition)
}
#[cfg(target_arch = "wasm32")]
{
if atomics_wait_supported() {
self.wait_block_timeout_while(guard, deadline, condition)
} else {
self.wait_spin_timeout_while(guard, deadline, condition)
}
}
}
/// Automatically chooses the right waiting strategy for your platform.
///
/// This is the recommended method as it papers over all platform differences:
/// - **Native**: Uses efficient thread parking
/// - **WASM with `Atomics.wait`**: Uses `Atomics.wait` for proper blocking
/// - **WASM without `Atomics.wait`**: Falls back to spinning (e.g., browser main thread)
///
/// You don't need to worry about "cannot block on main thread" errors -
/// this method handles that automatically by detecting the environment
/// and choosing the appropriate strategy.
///
/// # Spurious Wakeups
///
/// This method may return spuriously (without a notification). Always use it
/// in a loop that checks the condition.
///
/// # Examples
///
/// ```
/// # // std::thread::spawn panics on wasm32
/// # if cfg!(target_arch = "wasm32") { return; }
/// use wasm_safe_mutex::{Mutex, condvar::Condvar};
/// use std::sync::Arc;
/// # use std::thread;
///
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
/// let pair_clone = Arc::clone(&pair);
///
/// thread::spawn(move || {
/// let (mutex, condvar) = &*pair_clone;
/// let mut ready = mutex.lock_sync();
/// *ready = true;
/// drop(ready);
/// condvar.notify_one();
/// });
///
/// let (mutex, condvar) = &*pair;
/// let mut ready = mutex.lock_sync();
/// while !*ready {
/// ready = condvar.wait_sync(ready);
/// }
/// assert!(*ready);
/// ```
pub fn wait_sync<'a, T>(&self, guard: Guard<'a, T>) -> Guard<'a, T> {
#[cfg(not(target_arch = "wasm32"))]
{
self.wait_block(guard)
}
#[cfg(target_arch = "wasm32")]
{
if atomics_wait_supported() {
self.wait_block(guard)
} else {
// Fallback to spin lock if Atomics.wait is not supported
self.wait_spin(guard)
}
}
}
/// Automatically waits while the predicate is `true`, choosing the best strategy per platform.
///
/// This method blocks the current thread and waits for a notification as long as the
/// `condition` closure returns `true`. It automatically handles platform-specific
/// details to ensure the most efficient waiting mechanism is used.
///
/// # Platform Behavior
///
/// - **Native**: Uses efficient thread parking
/// - **WASM with `Atomics.wait`**: Uses `Atomics.wait` for proper blocking
/// - **WASM without `Atomics.wait`**: Falls back to spinning (e.g., browser main thread)
///
/// # Predicate
///
/// The `condition` closure is called:
/// 1. Before waiting (if it returns `false`, the method returns immediately)
/// 2. After each notification (to check if we should keep waiting)
/// 3. After spurious wakeups (to ensure we don't return prematurely)
///
/// # Spurious Wakeups
///
/// This method automatically handles spurious wakeups by re-checking the condition.
/// You do not need to loop around this call.
///
/// # Examples
///
/// ```
/// # // std::thread::spawn panics on wasm32
/// # if cfg!(target_arch = "wasm32") { return; }
/// use wasm_safe_mutex::{Mutex, condvar::Condvar};
/// use std::sync::Arc;
/// # use std::thread;
///
/// let pair = Arc::new((Mutex::new(false), Condvar::new()));
/// let pair_clone = Arc::clone(&pair);
///
/// thread::spawn(move || {
/// let (mutex, condvar) = &*pair_clone;
/// let mut ready = mutex.lock_sync();
/// *ready = true;
/// drop(ready);
/// condvar.notify_one();
/// });
///
/// let (mutex, condvar) = &*pair;
/// let mut ready = mutex.lock_sync();
/// // Wait until ready becomes true
/// ready = condvar.wait_sync_while(ready, |r| !*r);
/// assert!(*ready);
/// ```
pub fn wait_sync_while<'a, T, F>(
&self,
mut guard: Guard<'a, T>,
mut condition: F,
) -> Guard<'a, T>
where
F: FnMut(&mut T) -> bool,
{
#[cfg(not(target_arch = "wasm32"))]
{
while condition(&mut guard) {
guard = self.wait_block(guard);
}
guard
}
#[cfg(target_arch = "wasm32")]
{
if atomics_wait_supported() {
while condition(&mut guard) {
guard = self.wait_block(guard);
}
guard
} else {
while condition(&mut guard) {
guard = self.wait_spin(guard);
}
guard
}
}
}
}