kcas 0.1.0

A lock-free, allocation-free multi-word compare-and-swap library
Documentation
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
use core::ptr::NonNull;
use displaydoc::Display;

use tracing::instrument;

#[cfg(any(feature = "std", feature = "alloc"))]
use crate::sync::Arc;

use crate::err::Error;
use crate::kcas::{KCasWord, State};
use crate::sync::Ordering;
use crate::types::{
    convert_thread_id_to_thread_index, convert_thread_index_to_thread_id, ThreadIndex,
};

/// All thread slots for this [State] are already in use.
#[derive(Debug, Display)]
pub struct NoThreadIdAvailableError;

fn find_next_available_thread_index<const NUM_THREADS: usize, const NUM_WORDS: usize>(
    state: &State<NUM_THREADS, NUM_WORDS>,
) -> Result<ThreadIndex, NoThreadIdAvailableError> {
    for i in 0..NUM_THREADS {
        let cas_result: Result<bool, bool> = state.thread_index_slots[i].compare_exchange(
            false,
            true,
            Ordering::AcqRel,
            Ordering::Acquire,
        );

        if cas_result.is_ok() {
            state.num_threads_in_use.fetch_add(1, Ordering::AcqRel);
            return Ok(i);
        }
    }
    Err(NoThreadIdAvailableError)
}

/// An error which occurs while performing operations specific to [ArcStateWrapper], such as
/// attempting to construct one.
#[derive(Debug, Display)]
pub enum ArcStateWrapperError {
    /** Could not construct [ArcStateWrapper] because all thread slots for the provided [State] are
       already in use.
    */
    NoThreadIdAvailable(NoThreadIdAvailableError),
}

impl From<NoThreadIdAvailableError> for ArcStateWrapperError {
    fn from(error: NoThreadIdAvailableError) -> Self {
        Self::NoThreadIdAvailable(error)
    }
}

/// A wrapper for performing k-CAS operations which stores [State] inside an `Arc`. This makes it
/// convenient to use [ArcStateWrapper] when threads might outlive the functions which created them.
///
/// `NUM_THREADS` is the maximum number of threads which can run `kcas` on the provided [State].
/// `NUM_WORDS` is the number of words to operate on during each k-CAS operation.
#[derive(Debug)]
#[cfg(any(feature = "std", feature = "alloc"))]
pub struct ArcStateWrapper<const NUM_THREADS: usize, const NUM_WORDS: usize> {
    shared_state: Arc<State<NUM_THREADS, NUM_WORDS>>,
    thread_id: usize,
}

#[cfg(any(feature = "std", feature = "alloc"))]
impl<const NUM_THREADS: usize, const NUM_WORDS: usize> ArcStateWrapper<NUM_THREADS, NUM_WORDS> {
    /// Instantiate a new [ArcStateWrapper] and claim a thread slot in the provided [State]. This
    /// function fails if all thread slots for the provided [State] are already in use.
    pub fn construct(
        state: Arc<State<NUM_THREADS, NUM_WORDS>>,
    ) -> Result<Self, ArcStateWrapperError> {
        let state_ref: &State<NUM_THREADS, NUM_WORDS> = state.as_ref();

        let thread_index: ThreadIndex = find_next_available_thread_index(state_ref)?;
        Ok(Self {
            shared_state: state,
            thread_id: convert_thread_index_to_thread_id(thread_index),
        })
    }

    /// Perform a k-CAS operation on the target addresses specified in the provided [KCasWord]s in
    /// sequential order.
    #[instrument]
    pub fn kcas(&mut self, kcas_words: [KCasWord; NUM_WORDS]) -> Result<(), Error> {
        let shared_state: &State<NUM_THREADS, NUM_WORDS> = self.shared_state.as_ref();
        crate::kcas::kcas(shared_state, self.thread_id, kcas_words)
    }
}

#[cfg(any(feature = "std", feature = "alloc"))]
impl<const NUM_THREADS: usize, const NUM_WORDS: usize> Drop
    for ArcStateWrapper<NUM_THREADS, NUM_WORDS>
{
    fn drop(&mut self) {
        let thread_index: ThreadIndex = convert_thread_id_to_thread_index(self.thread_id);

        let shared_state_ref: &State<NUM_THREADS, NUM_WORDS> = self.shared_state.as_ref();
        shared_state_ref.thread_index_slots[thread_index].store(false, Ordering::Release);
        shared_state_ref
            .num_threads_in_use
            .fetch_min(1, Ordering::AcqRel);
    }
}

/// An error which occurs while performing operations specific to [RefStateWrapper], such as
/// attempting to construct one.
#[derive(Debug, Display)]
pub enum RefStateWrapperError {
    /** Could not construct [RefStateWrapper] because all thread slots for the provided [State]
       are already in use.
    */
    NoThreadIdAvailable(NoThreadIdAvailableError),
}

impl From<NoThreadIdAvailableError> for RefStateWrapperError {
    fn from(error: NoThreadIdAvailableError) -> Self {
        Self::NoThreadIdAvailable(error)
    }
}

/// A wrapper for performing k-CAS operations which stores [State] as a reference. This makes it
/// suited for scenarios where threads will not outlive the functions which created them.
///
/// `NUM_THREADS` is the maximum number of threads which can run `kcas` on the provided [State].
/// `NUM_WORDS` is the number of words to operate on during each k-CAS operation.
#[derive(Debug)]
pub struct RefStateWrapper<'a, const NUM_THREADS: usize, const NUM_WORDS: usize> {
    shared_state: &'a State<NUM_THREADS, NUM_WORDS>,
    thread_id: usize,
}

impl<'a, const NUM_THREADS: usize, const NUM_WORDS: usize>
    RefStateWrapper<'a, NUM_THREADS, NUM_WORDS>
{
    /// Instantiate a new [RefStateWrapper] and claim a thread slot in the provided [State]. This
    /// function fails if all thread slots for the provided [State] are already in use.
    pub fn construct(
        shared_state: &'a State<NUM_THREADS, NUM_WORDS>,
    ) -> Result<Self, RefStateWrapperError> {
        let thread_index: ThreadIndex = find_next_available_thread_index(shared_state)?;
        Ok(Self {
            shared_state,
            thread_id: convert_thread_index_to_thread_id(thread_index),
        })
    }

    /// Perform a k-CAS operation on the target addresses specified in the provided [KCasWord]s in
    /// sequential order.
    #[instrument]
    pub fn kcas(&mut self, kcas_words: [KCasWord; NUM_WORDS]) -> Result<(), Error> {
        crate::kcas::kcas(self.shared_state, self.thread_id, kcas_words)
    }
}

impl<'a, const NUM_THREADS: usize, const NUM_WORDS: usize> Drop
    for RefStateWrapper<'a, NUM_THREADS, NUM_WORDS>
{
    fn drop(&mut self) {
        let thread_index: ThreadIndex = convert_thread_id_to_thread_index(self.thread_id);

        self.shared_state.thread_index_slots[thread_index].store(false, Ordering::Release);
        self.shared_state
            .num_threads_in_use
            .fetch_min(1, Ordering::AcqRel);
    }
}

/// An error which occurs while performing operations specific to [UnsafeStateWrapper], such as
/// attempting to construct one.
#[derive(Debug, Display)]
pub enum UnsafeStateWrapperError {
    /** Could not construct [UnsafeStateWrapper] because all thread slots for the provided [State]
          are already in use.
    */
    NoThreadIdAvailable(NoThreadIdAvailableError),
}

impl From<NoThreadIdAvailableError> for UnsafeStateWrapperError {
    fn from(error: NoThreadIdAvailableError) -> Self {
        Self::NoThreadIdAvailable(error)
    }
}

/// A wrapper for performing k-CAS operations which stores [State] as an unsafe [NonNull]. This
/// makes it suited for scenarios where the user would like complete control over where the [State]
/// lives and how it is made available across threads. The user is responsible for dropping
/// [State] after all threads are finished using it.
///
/// `NUM_THREADS` is the maximum number of threads which can run `kcas` on the provided [State].
/// `NUM_WORDS` is the number of words to operate on during each k-CAS operation.
#[derive(Debug)]
pub struct UnsafeStateWrapper<const NUM_THREADS: usize, const NUM_WORDS: usize> {
    shared_state: NonNull<State<NUM_THREADS, NUM_WORDS>>,
    thread_id: usize,
}

impl<const NUM_THREADS: usize, const NUM_WORDS: usize> UnsafeStateWrapper<NUM_THREADS, NUM_WORDS> {
    /// Instantiate a new [UnsafeStateWrapper] and claim a thread slot in the provided [State]. This
    /// function fails if all thread slots for the provided [State] are already in use.
    pub fn construct(
        shared_state: NonNull<State<NUM_THREADS, NUM_WORDS>>,
    ) -> Result<Self, UnsafeStateWrapperError> {
        let shared_state_ref = unsafe { shared_state.as_ref() };
        let thread_index: ThreadIndex = find_next_available_thread_index(shared_state_ref)?;
        Ok(Self {
            shared_state,
            thread_id: convert_thread_index_to_thread_id(thread_index),
        })
    }

    /// Perform a k-CAS operation on the target addresses specified in the provided [KCasWord]s in
    /// sequential order.
    #[instrument]
    pub fn kcas(&mut self, kcas_words: [KCasWord; NUM_WORDS]) -> Result<(), Error> {
        let shared_state: &State<NUM_THREADS, NUM_WORDS> = unsafe { self.shared_state.as_ref() };
        crate::kcas::kcas(shared_state, self.thread_id, kcas_words)
    }
}

impl<const NUM_THREADS: usize, const NUM_WORDS: usize> Drop
    for UnsafeStateWrapper<NUM_THREADS, NUM_WORDS>
{
    fn drop(&mut self) {
        let thread_index: ThreadIndex = convert_thread_id_to_thread_index(self.thread_id);

        let shared_state: &State<NUM_THREADS, NUM_WORDS> = unsafe { self.shared_state.as_ref() };
        shared_state.thread_index_slots[thread_index].store(false, Ordering::Release);
        shared_state
            .num_threads_in_use
            .fetch_min(1, Ordering::AcqRel);
    }
}

unsafe impl<const NUM_THREADS: usize, const NUM_WORDS: usize> Send for UnsafeStateWrapper<NUM_THREADS, NUM_WORDS> {}
unsafe impl<const NUM_THREADS: usize, const NUM_WORDS: usize> Sync for UnsafeStateWrapper<NUM_THREADS, NUM_WORDS> {}

#[cfg(all(test, feature = "std", not(feature = "shuttle"), not(loom)))]
mod tests {
    use crate::err::Error;
    use crate::kcas::{KCasWord, State};
    use crate::sync::{Arc, AtomicUsize, Ordering};
    use crate::wrapper::{
        ArcStateWrapper, ArcStateWrapperError, RefStateWrapper, RefStateWrapperError,
        UnsafeStateWrapper, UnsafeStateWrapperError,
    };
    use std::ptr::NonNull;
    use std::thread;
    use std::thread::ScopedJoinHandle;
    use test_log::test;

    #[test]
    fn test_arc_state_wrapper_thread_reservation() {
        let state: State<3, 3> = State::new();
        let state_arc: Arc<State<3, 3>> = Arc::new(state);

        let first_wrapper: ArcStateWrapper<3, 3> =
            ArcStateWrapper::construct(state_arc.clone()).unwrap();
        assert_eq!(first_wrapper.thread_id, 1);
        {
            let second_wrapper = ArcStateWrapper::construct(state_arc.clone()).unwrap();
            assert_eq!(second_wrapper.thread_id, 2);
        }
        // the second wrapper as been dropped - thread id 2 should be available again
        let second_wrapper: ArcStateWrapper<3, 3> =
            ArcStateWrapper::construct(state_arc.clone()).unwrap();
        assert_eq!(second_wrapper.thread_id, 2);

        let third_wrapper: ArcStateWrapper<3, 3> =
            ArcStateWrapper::construct(state_arc.clone()).unwrap();
        assert_eq!(third_wrapper.thread_id, 3);

        // now there should be no thread ids left
        let result: Result<ArcStateWrapper<3, 3>, ArcStateWrapperError> =
            ArcStateWrapper::construct(state_arc.clone());
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            ArcStateWrapperError::NoThreadIdAvailable(_)
        ));
    }

    #[test]
    fn test_ref_state_wrapper_thread_reservation() {
        let state: State<3, 3> = State::new();

        let first_wrapper: RefStateWrapper<3, 3> = RefStateWrapper::construct(&state).unwrap();
        assert_eq!(first_wrapper.thread_id, 1);
        {
            let second_wrapper: RefStateWrapper<3, 3> = RefStateWrapper::construct(&state).unwrap();
            assert_eq!(second_wrapper.thread_id, 2);
        }
        // the second wrapper as been dropped - thread id 2 should be available again
        let second_wrapper: RefStateWrapper<3, 3> = RefStateWrapper::construct(&state).unwrap();
        assert_eq!(second_wrapper.thread_id, 2);

        let third_wrapper: RefStateWrapper<3, 3> = RefStateWrapper::construct(&state).unwrap();
        assert_eq!(third_wrapper.thread_id, 3);

        // now there should be no thread ids left
        let result: Result<RefStateWrapper<3, 3>, RefStateWrapperError> =
            RefStateWrapper::construct(&state);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            RefStateWrapperError::NoThreadIdAvailable(_)
        ));
    }

    #[test]
    fn test_unsafe_state_wrapper_thread_reservation() {
        let state: State<3, 3> = State::new();
        let non_null_state: NonNull<State<3, 3>> = NonNull::from(&state);

        let first_wrapper: UnsafeStateWrapper<3, 3> =
            UnsafeStateWrapper::construct(non_null_state).unwrap();
        assert_eq!(first_wrapper.thread_id, 1);
        {
            let second_wrapper: UnsafeStateWrapper<3, 3> =
                UnsafeStateWrapper::construct(non_null_state).unwrap();
            assert_eq!(second_wrapper.thread_id, 2);
        }
        // the second wrapper as been dropped - thread id 2 should be available again
        let second_wrapper: UnsafeStateWrapper<3, 3> =
            UnsafeStateWrapper::construct(non_null_state).unwrap();
        assert_eq!(second_wrapper.thread_id, 2);

        let third_wrapper: UnsafeStateWrapper<3, 3> =
            UnsafeStateWrapper::construct(non_null_state).unwrap();
        assert_eq!(third_wrapper.thread_id, 3);

        // now there should be no thread ids left
        let result: Result<UnsafeStateWrapper<3, 3>, UnsafeStateWrapperError> =
            UnsafeStateWrapper::construct(non_null_state);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            UnsafeStateWrapperError::NoThreadIdAvailable(_)
        ));
    }

    #[test]
    fn test_arc_state_wrapper_with_2_threads() {
        test_arc_state_wrapper::<2, 3>();
    }

    fn test_arc_state_wrapper<const NUM_THREADS: usize, const NUM_WORDS: usize>() {
        let state: State<NUM_THREADS, NUM_WORDS> = State::new();
        let state_arc: Arc<State<NUM_THREADS, NUM_WORDS>> = Arc::new(state);

        let targets: [Arc<AtomicUsize>; NUM_WORDS] =
            core::array::from_fn(|_| Arc::new(AtomicUsize::new(0)));

        let join_handles: Vec<thread::JoinHandle<Result<(), Error>>> = (0..NUM_THREADS)
            .map(|i| {
                let mut wrapper: ArcStateWrapper<NUM_THREADS, NUM_WORDS> =
                    ArcStateWrapper::construct(state_arc.clone()).unwrap();
                let cloned_targets: Vec<Arc<AtomicUsize>> = targets
                    .iter()
                    .cloned()
                    .collect();
                let handle: thread::JoinHandle<Result<(), Error>> = thread::spawn(move || {
                    let cloned_targets = cloned_targets;
                    let kcas_words: Vec<KCasWord> = cloned_targets
                        .iter()
                        .map(|target_arc| KCasWord::new(target_arc.as_ref(), 0, i))
                        .collect();
                    let kcas_words: [KCasWord; NUM_WORDS] = kcas_words.try_into().unwrap();
                    wrapper.kcas(kcas_words)
                });
                handle
            })
            .collect();

        join_handles.into_iter().for_each(|join_handle| {
            let result: Result<(), Error> = join_handle.join().expect("A thread panicked");
            assert!(matches!(result, Ok(_)) || matches!(result, Err(Error::ValueWasNotExpectedValue)));
        });
        assert!((0..NUM_THREADS).any(|i| targets
            .iter()
            .all(|target| target.load(Ordering::Acquire) == i)));
    }

    #[test]
    fn test_ref_state_wrapper_with_2_threads() {
        test_ref_state_wrapper::<2, 3>();
    }

    fn test_ref_state_wrapper<const NUM_THREADS: usize, const NUM_WORDS: usize>() {
        let state: State<NUM_THREADS, NUM_WORDS> = State::new();

        let targets: [Arc<AtomicUsize>; NUM_WORDS] =
            core::array::from_fn(|_| Arc::new(AtomicUsize::new(0)));

        thread::scope(|scope| {
            let join_handles: Vec<ScopedJoinHandle<Result<(), Error>>> = (0..NUM_THREADS)
                .map(|i| {
                    let mut wrapper: RefStateWrapper<NUM_THREADS, NUM_WORDS> =
                        RefStateWrapper::construct(&state).unwrap();
                    let cloned_targets: Vec<Arc<AtomicUsize>> = targets
                        .iter()
                        .cloned()
                        .collect();
                    let handle: ScopedJoinHandle<Result<(), Error>> = scope.spawn(move || {
                        let cloned_targets = cloned_targets;
                        let kcas_words: Vec<KCasWord> = cloned_targets
                            .iter()
                            .map(|target_arc| KCasWord::new(target_arc.as_ref(), 0, i))
                            .collect();
                        let kcas_words: [KCasWord; NUM_WORDS] = kcas_words.try_into().unwrap();
                        wrapper.kcas(kcas_words)
                    });
                    handle
                })
                .collect();

            join_handles.into_iter().for_each(|join_handle| {
                let result: Result<(), Error> = join_handle.join().expect("A thread panicked");
                assert!(matches!(result, Ok(_)) || matches!(result, Err(Error::ValueWasNotExpectedValue)));
            });
        });

        assert!((0..NUM_THREADS).any(|i| targets
            .iter()
            .all(|target| target.load(Ordering::Acquire) == i)));
    }

    #[test]
    fn test_unsafe_state_wrapper_with_2_threads() {
        test_unsafe_state_wrapper::<2, 3>();
    }

    fn test_unsafe_state_wrapper<const NUM_THREADS: usize, const NUM_WORDS: usize>() {
        let state: State<NUM_THREADS, NUM_WORDS> = State::new();
        let state_pointer: NonNull<State<NUM_THREADS, NUM_WORDS>> = NonNull::from(&state);

        let targets: [Arc<AtomicUsize>; NUM_WORDS] =
            core::array::from_fn(|_| Arc::new(AtomicUsize::new(0)));

        thread::scope(|scope| {
            let join_handles: Vec<ScopedJoinHandle<Result<(), Error>>> = (0..NUM_THREADS)
                .map(|i| {
                    let mut wrapper: UnsafeStateWrapper<NUM_THREADS, NUM_WORDS> =
                        UnsafeStateWrapper::construct(state_pointer).unwrap();
                    let cloned_targets: Vec<Arc<AtomicUsize>> = targets
                        .iter()
                        .cloned()
                        .collect();
                    let handle: ScopedJoinHandle<Result<(), Error>> = scope.spawn(move || {
                        let cloned_targets = cloned_targets;
                        let kcas_words: Vec<KCasWord> = cloned_targets
                            .iter()
                            .map(|target_arc| KCasWord::new(target_arc.as_ref(), 0, i))
                            .collect();
                        let kcas_words: [KCasWord; NUM_WORDS] = kcas_words.try_into().unwrap();
                        wrapper.kcas(kcas_words)
                    });
                    handle
                })
                .collect();

            join_handles.into_iter().for_each(|join_handle| {
                let result: Result<(), Error> = join_handle.join().expect("A thread panicked");
                assert!(matches!(result, Ok(_)) || matches!(result, Err(Error::ValueWasNotExpectedValue)));
            });
        });

        assert!((0..NUM_THREADS).any(|i| targets
            .iter()
            .all(|target| target.load(Ordering::Acquire) == i)));
    }
}