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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
//! Types for working with Ruby mutexes.
use std::{fmt, time::Duration};
use rb_sys::{
rb_mutex_lock, rb_mutex_locked_p, rb_mutex_new, rb_mutex_sleep, rb_mutex_synchronize,
rb_mutex_trylock, rb_mutex_unlock, VALUE,
};
use crate::{
class::RClass,
error::{protect, Error},
into_value::IntoValue,
method::{BlockReturn, Synchronize},
object::Object,
r_typed_data::RTypedData,
try_convert::TryConvert,
value::{
private::{self, ReprValue as _},
ReprValue, Value,
},
Ruby,
};
/// # `Mutex`
///
/// Functions that can be used to create Ruby `Mutex`s.
///
/// See also the [`Mutex`] type.
impl Ruby {
/// Create a Ruby Mutex.
///
/// # Examples
///
/// ```
/// use magnus::{Error, Ruby};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let lock = ruby.mutex_new();
/// assert!(!lock.is_locked());
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn mutex_new(&self) -> Mutex {
unsafe { Mutex::from_rb_value_unchecked(rb_mutex_new()) }
}
}
/// Wrapper type for a Value known to be an instance of Ruby's Mutex class.
///
/// See the [`ReprValue`] and [`Object`] traits for additional methods
/// available on this type. See [`Ruby`](Ruby#mutex) for methods to create a
/// `Mutex`.
#[derive(Clone, Copy)]
#[repr(transparent)]
pub struct Mutex(RTypedData);
impl Mutex {
/// Return `Some(Mutex)` if `val` is a `Mutex`, `None` otherwise.
///
/// # Examples
///
/// ```
/// use magnus::eval;
/// # let _cleanup = unsafe { magnus::embed::init() };
///
/// assert!(magnus::Mutex::from_value(eval("Mutex.new").unwrap()).is_some());
/// assert!(magnus::Mutex::from_value(eval("true").unwrap()).is_none());
/// ```
#[inline]
pub fn from_value(val: Value) -> Option<Self> {
let mutex_class: RClass = Ruby::get_with(val)
.class_object()
.funcall("const_get", ("Mutex",))
.ok()?;
RTypedData::from_value(val)
.filter(|_| val.is_kind_of(mutex_class))
.map(Self)
}
#[inline]
pub(crate) unsafe fn from_rb_value_unchecked(val: VALUE) -> Self {
Self(RTypedData::from_rb_value_unchecked(val))
}
/// Returns whether any threads currently hold the lock.
///
/// # Examples
///
/// ```
/// use magnus::{Error, Ruby};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let lock = ruby.mutex_new();
/// assert!(!lock.is_locked());
///
/// lock.lock()?;
/// assert!(lock.is_locked());
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn is_locked(self) -> bool {
unsafe { Value::new(rb_mutex_locked_p(self.as_rb_value())).to_bool() }
}
/// Attempts to acquire the lock.
///
/// This method does not block. Returns true if the lock can be acquired,
/// false otherwise.
///
/// # Examples
///
/// ```
/// use magnus::{Error, Ruby};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let lock = ruby.mutex_new();
///
/// assert!(lock.trylock());
/// assert!(lock.is_locked());
///
/// assert!(!lock.trylock());
/// assert!(lock.is_locked());
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn trylock(self) -> bool {
unsafe { Value::new(rb_mutex_trylock(self.as_rb_value())).to_bool() }
}
/// Acquires the lock.
///
/// This method will block the current thread until the lock can be
/// acquired. Returns `Err` on deadlock.
///
/// # Examples
///
/// ```
/// use magnus::{Error, Ruby};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let lock = ruby.mutex_new();
///
/// lock.lock()?;
/// assert!(lock.is_locked());
///
/// assert!(lock.lock().is_err());
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn lock(self) -> Result<(), Error> {
protect(|| unsafe { Value::new(rb_mutex_lock(self.as_rb_value())) })?;
Ok(())
}
/// Release the lock.
///
/// Returns `Err` if the current thread does not own the lock.
///
/// # Examples
///
/// ```
/// use magnus::{Error, Ruby};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let lock = ruby.mutex_new();
/// lock.lock()?;
/// assert!(lock.is_locked());
///
/// lock.unlock()?;
/// assert!(!lock.is_locked());
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn unlock(self) -> Result<(), Error> {
protect(|| unsafe { Value::new(rb_mutex_unlock(self.as_rb_value())) })?;
Ok(())
}
/// Release the lock for `timeout`, reaquiring it on wakeup.
///
/// Returns `Err` if the current thread does not own the lock.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
///
/// use magnus::{Error, Ruby};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let lock = ruby.mutex_new();
/// lock.lock()?;
/// lock.sleep(Some(Duration::from_millis(10)))?;
/// lock.unlock()?;
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn sleep(self, timeout: Option<Duration>) -> Result<(), Error> {
let ruby = Ruby::get_with(self);
protect(|| unsafe {
Value::new(rb_mutex_sleep(
self.as_rb_value(),
ruby.into_value(timeout.map(|d| d.as_secs_f64()))
.as_rb_value(),
))
})?;
Ok(())
}
/// Acquires the lock, runs `func`, then releases the lock.
///
/// # Examples
///
/// ```
/// use magnus::{Error, Ruby, Value};
///
/// fn example(ruby: &Ruby) -> Result<(), Error> {
/// let lock = ruby.mutex_new();
/// let mut i = 0;
/// let _: Value = lock.synchronize(|| i += 1)?;
/// assert_eq!(1, i);
///
/// Ok(())
/// }
/// # Ruby::init(example).unwrap()
/// ```
pub fn synchronize<F, R, T>(self, func: F) -> Result<T, Error>
where
F: FnOnce() -> R,
R: BlockReturn,
T: TryConvert,
{
unsafe extern "C" fn call<F, R>(arg: VALUE) -> VALUE
where
F: FnOnce() -> R,
R: BlockReturn,
{
let closure = (*(arg as *mut Option<F>)).take().unwrap();
closure.call_handle_error().as_rb_value()
}
protect(|| unsafe {
let mut some_func = Some(func);
let closure = &mut some_func as *mut Option<F> as VALUE;
Value::new(rb_mutex_synchronize(
self.as_rb_value(),
Some(call::<F, R>),
closure,
))
})
.and_then(TryConvert::try_convert)
}
}
impl fmt::Display for Mutex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", unsafe { self.to_s_infallible() })
}
}
impl fmt::Debug for Mutex {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.inspect())
}
}
impl IntoValue for Mutex {
#[inline]
fn into_value_with(self, _: &Ruby) -> Value {
self.0.as_value()
}
}
impl Object for Mutex {}
unsafe impl private::ReprValue for Mutex {}
impl ReprValue for Mutex {}
impl TryConvert for Mutex {
fn try_convert(val: Value) -> Result<Self, Error> {
Self::from_value(val).ok_or_else(|| {
Error::new(
Ruby::get_with(val).exception_type_error(),
format!("no implicit conversion of {} into Mutex", unsafe {
val.classname()
},),
)
})
}
}