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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
// Unless explicitly stated otherwise all files in this repository are licensed
// under the MIT/Apache-2.0 License, at your convenience
//
// This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2020 Datadog, Inc.
//
use crate::error::{GlommioError, ResourceType};
use std::{
    cell::RefCell,
    future::Future,
    pin::Pin,
    task::{Context, Poll, Waker},
};

use intrusive_collections::{
    container_of,
    linked_list::LinkOps,
    offset_of,
    Adapter,
    LinkedList,
    LinkedListLink,
    PointerOps,
};
use std::{marker::PhantomPinned, ptr::NonNull, rc::Rc};

type Result<T> = crate::error::Result<T, ()>;

#[derive(Debug)]
struct Waiter<'a> {
    node: WaiterNode,
    semaphore: &'a Semaphore,
}

#[derive(Debug)]
struct WaiterNode {
    link: LinkedListLink,
    units: u64,
    waker: RefCell<Option<Waker>>,

    //waiter node can not be Unpin so its pointer could be used inside of intrusive
    //collection, it also can not outlive the container which is guaranteed by the
    //Waiter lifetime bound to the Semaphore which is container of all Waiters.
    _p: PhantomPinned,
}

struct WaiterPointerOps;

unsafe impl PointerOps for WaiterPointerOps {
    type Value = WaiterNode;
    type Pointer = NonNull<WaiterNode>;

    unsafe fn from_raw(&self, value: *const Self::Value) -> Self::Pointer {
        NonNull::new(value as *mut Self::Value).expect("Passed in Pointer can not be null")
    }

    fn into_raw(&self, ptr: Self::Pointer) -> *const Self::Value {
        ptr.as_ptr() as *const Self::Value
    }
}

struct WaiterAdapter {
    pointers_ops: WaiterPointerOps,
    link_ops: LinkOps,
}

impl WaiterAdapter {
    fn new() -> Self {
        WaiterAdapter {
            pointers_ops: WaiterPointerOps,
            link_ops: LinkOps,
        }
    }
}

unsafe impl Adapter for WaiterAdapter {
    type LinkOps = LinkOps;
    type PointerOps = WaiterPointerOps;

    unsafe fn get_value(
        &self,
        link: <Self::LinkOps as intrusive_collections::LinkOps>::LinkPtr,
    ) -> *const <Self::PointerOps as PointerOps>::Value {
        container_of!(link.as_ptr(), WaiterNode, link)
    }

    unsafe fn get_link(
        &self,
        value: *const <Self::PointerOps as PointerOps>::Value,
    ) -> <Self::LinkOps as intrusive_collections::LinkOps>::LinkPtr {
        if value.is_null() {
            panic!("Passed in pointer to the value can not be null");
        }

        let ptr = (value as *const u8).add(offset_of!(WaiterNode, link));
        //we call unchecked method because of safety check above
        core::ptr::NonNull::new_unchecked(ptr as *mut _)
    }

    fn link_ops(&self) -> &Self::LinkOps {
        &self.link_ops
    }

    fn link_ops_mut(&mut self) -> &mut Self::LinkOps {
        &mut self.link_ops
    }

    fn pointer_ops(&self) -> &Self::PointerOps {
        &self.pointers_ops
    }
}

impl<'a> Waiter<'a> {
    fn new(units: u64, semaphore: &'a Semaphore) -> Waiter<'a> {
        Waiter {
            node: WaiterNode {
                link: LinkedListLink::new(),
                units,
                waker: RefCell::new(None),
                _p: PhantomPinned,
            },
            semaphore,
        }
    }

    fn remove_from_waiting_queue(
        waiter_node: Pin<&mut WaiterNode>,
        sem_state: &mut SemaphoreState,
    ) {
        if waiter_node.link.is_linked() {
            let mut cursor = unsafe {
                sem_state
                    .waiters_list
                    .cursor_mut_from_ptr(Pin::into_inner_unchecked(waiter_node) as *const _)
            };

            if cursor.remove().is_none() {
                panic!("Waiter has to be linked into the list of waiting futures");
            }
        }
    }

    fn register_in_waiting_queue(
        waiter_node: Pin<&mut WaiterNode>,
        sem_state: &mut SemaphoreState,
        waker: Waker,
    ) {
        *waiter_node.waker.borrow_mut() = Some(waker);

        if waiter_node.link.is_linked() {
            return;
        }

        sem_state.waiters_list.push_back(unsafe {
            //it is safe to use unchecked call here because we convert passed in reference
            // which can not be null
            NonNull::new_unchecked(Pin::into_inner_unchecked(waiter_node) as *mut _)
        });
    }
}

impl<'a> Drop for Waiter<'a> {
    fn drop(&mut self) {
        if self.node.link.is_linked() {
            //if node is linked that is for sure is pinned so that is safe
            //to make it pinned directly
            let waiter_node = unsafe { Pin::new_unchecked(&mut self.node) };
            Self::remove_from_waiting_queue(waiter_node, &mut self.semaphore.state.borrow_mut())
        }
    }
}

impl<'a> Future for Waiter<'a> {
    type Output = Result<()>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let mut sem_state = self.semaphore.state.borrow_mut();
        let future_mut = unsafe { self.get_unchecked_mut() };

        let waiter_node = unsafe { Pin::new_unchecked(&mut future_mut.node) };

        let units = waiter_node.units;
        match sem_state.try_acquire(units) {
            Err(x) => {
                Self::remove_from_waiting_queue(waiter_node, &mut sem_state);
                Poll::Ready(Err(x))
            }
            Ok(true) => {
                Self::remove_from_waiting_queue(waiter_node, &mut sem_state);
                Poll::Ready(Ok(()))
            }
            Ok(false) => {
                Self::register_in_waiting_queue(waiter_node, &mut sem_state, cx.waker().clone());
                Poll::Pending
            }
        }
    }
}

#[derive(Debug)]
struct SemaphoreState {
    avail: u64,
    closed: bool,
    waiters_list: LinkedList<WaiterAdapter>,
}

impl SemaphoreState {
    fn new(avail: u64) -> Self {
        SemaphoreState {
            avail,
            closed: false,
            waiters_list: LinkedList::new(WaiterAdapter::new()),
        }
    }

    fn available(&self) -> u64 {
        self.avail
    }

    fn try_acquire(&mut self, units: u64) -> Result<bool> {
        if self.closed {
            return Err(GlommioError::Closed(ResourceType::Semaphore {
                requested: units,
                available: self.avail,
            }));
        }

        if self.avail >= units {
            self.avail -= units;
            return Ok(true);
        }
        Ok(false)
    }

    fn close(&mut self) {
        self.closed = true;

        let mut cursor = self.waiters_list.front_mut();
        while !cursor.is_null() {
            let node = cursor.remove().unwrap();

            let node = unsafe { Pin::new_unchecked(&*node.as_ptr()) };
            let waker = node.waker.borrow_mut().take();
            if let Some(waker) = waker {
                waker.wake();
            } else {
                panic!("Future is linked into the waiting list without a waker");
            }
        }
    }

    fn signal(&mut self, units: u64) {
        self.avail += units;
    }
}

/// The permit is A RAII-friendly way to acquire semaphore resources.
///
/// Resources are held while the Permit is alive, and released when the
/// permit is dropped.
#[derive(Debug)]
#[must_use = "units are only held while the permit is alive. If unused then semaphore will \
              immediately release units"]
pub struct Permit<'a> {
    units: u64,
    sem: &'a Semaphore,
}

/// The static permit is A RAII-friendly way to acquire semaphore resources in
/// long-lived operations that require a static lifetime.
///
/// Resources are held while the Permit is alive, and released when the
/// permit is dropped.
#[derive(Debug)]
pub struct StaticPermit {
    units: u64,
    sem: Rc<Semaphore>,
}

impl<'a> Permit<'a> {
    fn new(units: u64, sem: &'a Semaphore) -> Permit<'a> {
        Permit { units, sem }
    }
}

impl StaticPermit {
    fn new(units: u64, sem: Rc<Semaphore>) -> StaticPermit {
        StaticPermit { units, sem }
    }

    /// Closes the underlying semaphore that originated this permit.
    pub fn close(&self) {
        self.sem.close()
    }
}

impl<'a> Drop for Permit<'a> {
    fn drop(&mut self) {
        process_wakes(self.sem, self.units);
    }
}

impl Drop for StaticPermit {
    fn drop(&mut self) {
        process_wakes(&self.sem, self.units);
    }
}

fn process_wakes(sem: &Semaphore, units: u64) {
    let mut state = sem.state.borrow_mut();
    state.signal(units);

    let mut available_units = state.avail;

    let mut cursor = state.waiters_list.front_mut();

    //only tasks which will be able to proceed will be awaken
    while available_units > 0 {
        let mut waker = None;
        if let Some(node) = cursor.get() {
            let node = unsafe { Pin::new_unchecked(node) };

            if node.units <= available_units {
                let w = node.waker.borrow_mut().take();

                if w.is_some() {
                    waker = w;
                } else {
                    panic!("Future was linked into the waiting list without a waker");
                }

                available_units -= node.units;
            }
        } else {
            break;
        }

        if let Some(waker) = waker {
            waker.wake();
            cursor.remove();
        } else {
            cursor.move_next();
        }
    }
}

/// An implementation of semaphore that doesn't use helper threads,
/// condition variables, and is friendly to single-threaded execution.
#[derive(Debug)]
pub struct Semaphore {
    state: RefCell<SemaphoreState>,
}

impl Semaphore {
    /// Creates a new semaphore with the specified amount of units
    ///
    /// # Examples
    ///
    /// ```
    /// use glommio::sync::Semaphore;
    ///
    /// let _ = Semaphore::new(1);
    /// ```
    pub fn new(avail: u64) -> Semaphore {
        Semaphore {
            state: RefCell::new(SemaphoreState::new(avail)),
        }
    }

    /// Returns the amount of units currently available in this semaphore
    ///
    /// # Examples
    ///
    /// ```
    /// use glommio::sync::Semaphore;
    ///
    /// let sem = Semaphore::new(1);
    /// assert_eq!(sem.available(), 1);
    /// ```
    pub fn available(&self) -> u64 {
        self.state.borrow().available()
    }

    /// Suspends until a permit can be acquired with the specified amount of
    /// units.
    ///
    /// Returns Err() if the semaphore is closed during the wait.
    ///
    /// Similar to [`acquire_static_permit`], except that it requires the permit
    /// never to be passed to contexts that require a static lifetime. As
    /// this is cheaper than [`acquire_static_permit`], it is useful in
    /// situations where the permit tracks an a asynchronous operation whose
    /// lifetime is simple and well-defined.
    ///
    /// # Examples
    ///
    /// ```
    /// use glommio::{sync::Semaphore, LocalExecutor};
    ///
    /// let sem = Semaphore::new(1);
    ///
    /// let ex = LocalExecutor::default();
    /// ex.run(async move {
    ///     {
    ///         let permit = sem.acquire_permit(1).await.unwrap();
    ///         // once it is dropped it can be acquired again
    ///         // going out of scope will drop
    ///     }
    ///     let _guard = sem.acquire_permit(1).await.unwrap();
    /// });
    /// ```
    ///
    /// [`acquire_static_permit`]: Semaphore::acquire_static_permit
    pub async fn acquire_permit(&self, units: u64) -> Result<Permit<'_>> {
        self.acquire(units).await?;
        Ok(Permit::new(units, self))
    }

    /// Suspends until a permit can be acquired with the specified amount of
    /// units.
    ///
    /// Returns Err() if the semaphore is closed during the wait.
    ///
    /// Similar to [`acquire_permit`], except that it requires the semaphore to
    /// be contained in an [`Rc`]. This is useful in situations where the
    /// permit tracks a long-lived asynchronous operation whose lifetime is
    /// complex.
    ///
    /// # Examples
    ///
    /// ```
    /// use glommio::{sync::Semaphore, timer::sleep, Local, LocalExecutor};
    /// use std::{rc::Rc, time::Duration};
    ///
    /// let sem = Rc::new(Semaphore::new(1));
    ///
    /// let ex = LocalExecutor::default();
    /// ex.run(async move {
    ///     {
    ///         let permit = sem.acquire_static_permit(1).await.unwrap();
    ///         Local::local(async move {
    ///             let _guard = permit;
    ///             sleep(Duration::from_secs(1)).await;
    ///         })
    ///         .detach();
    ///         // once it is dropped it can be acquired again
    ///         // going out of scope will drop
    ///     }
    ///     let _guard = sem.acquire_permit(1).await.unwrap();
    /// });
    /// ```
    ///
    /// [`acquire_permit`]: Semaphore::acquire_permit
    /// [`Rc`]: https://doc.rust-lang.org/std/rc/struct.Rc.html
    pub async fn acquire_static_permit(self: &Rc<Self>, units: u64) -> Result<StaticPermit> {
        self.acquire(units).await?;
        Ok(StaticPermit::new(units, self.clone()))
    }

    /// Acquires the specified amount of units from this semaphore.
    ///
    /// The caller is then responsible to release units. Whenever possible,
    /// prefer acquire_permit().
    ///
    /// # Examples
    ///
    /// ```
    /// use glommio::{sync::Semaphore, LocalExecutor};
    ///
    /// let sem = Semaphore::new(1);
    ///
    /// let ex = LocalExecutor::default();
    /// ex.run(async move {
    ///     sem.acquire(1).await.unwrap();
    ///     sem.signal(1); // Has to be signaled explicitly. Be careful
    /// });
    /// ```
    pub async fn acquire(&self, units: u64) -> Result<()> {
        let waiter = {
            let mut state = self.state.borrow_mut();
            // Try acquiring first without paying the price to construct a waker.
            // If that fails then we construct a waker and wait on it.
            if state.waiters_list.is_empty() && state.try_acquire(units)? {
                return Ok(());
            }
            Waiter::new(units, self)
        };

        waiter.await
    }

    /// Acquires the given number of units, if they are available, and
    /// returns immediately, with the value true,
    /// reducing the number of available units by the given amount.
    ///
    /// If insufficient units are available then this method will return
    /// immediately with the value `false` and the number of available
    /// permits is unchanged.
    ///
    /// This method does not suspend.
    ///
    /// The caller is then responsible to release units. Whenever possible,
    /// prefer [`try_acquire_permit`].
    ///
    /// # Errors
    ///
    /// If semaphore is closed `Err(io::Error(BrokenPipe))` will be returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use glommio::{sync::Semaphore, LocalExecutor};
    ///
    /// let sem = Semaphore::new(1);
    ///
    /// let ex = LocalExecutor::default();
    ///
    /// ex.run(async move {
    ///     assert!(sem.try_acquire(1).unwrap());
    ///     sem.signal(1); // Has to be signaled explicitly. Be careful
    /// });
    /// ```
    ///
    /// [`try_acquire_permit`]: Semaphore::try_acquire_permit
    pub fn try_acquire(&self, units: u64) -> Result<bool> {
        let mut state = self.state.borrow_mut();

        if state.waiters_list.is_empty() && state.try_acquire(units)? {
            return Ok(true);
        }

        Ok(false)
    }

    /// Acquires the given number of units, if they are available, and
    /// returns immediately, with the RAAI guard,
    /// reducing the number of available units by the given amount.
    ///
    /// If insufficient units are available then this method will return
    /// `Err` and the number of available permits is unchanged.
    ///
    /// This method does not suspend.
    ///
    /// # Errors
    ///  If semaphore is closed
    /// `Err(GlommioError::Closed(ResourceType::Semaphore { .. }))` will be
    /// returned.  If semaphore does not have sufficient amount of units
    ///  `
    ///  Err(GlommioError::WouldBlock(ResourceType::Semaphore {
    ///      requested: u64,
    ///      available: u64
    ///  }))
    ///  `
    ///  will be returned.
    ///
    /// # Examples
    ///
    /// ```
    /// use glommio::{sync::Semaphore, LocalExecutor};
    ///
    /// let sem = Semaphore::new(1);
    ///
    /// let ex = LocalExecutor::default();
    ///
    /// ex.run(async move {
    ///     let permit = sem.acquire_permit(1).await.unwrap();
    ///     // once it is dropped it can be acquired again
    ///     // going out of scope will drop
    /// });
    /// ```
    pub fn try_acquire_permit(&self, units: u64) -> Result<Permit<'_>> {
        let mut state = self.state.borrow_mut();

        if state.waiters_list.is_empty() && state.try_acquire(units)? {
            return Ok(Permit::new(units, self));
        }
        Err(GlommioError::WouldBlock(ResourceType::Semaphore {
            requested: units,
            available: state.available(),
        }))
    }

    /// Signals the semaphore to release the specified amount of units.
    ///
    /// This needs to be paired with a call to acquire(). You should not
    /// call this if the units were acquired with acquire_permit().
    ///
    /// # Examples
    ///
    /// ```
    /// use glommio::{sync::Semaphore, LocalExecutor};
    ///
    /// let sem = Semaphore::new(0);
    ///
    /// let ex = LocalExecutor::default();
    /// ex.run(async move {
    ///     // Note that we can signal to expand to more units than the original capacity had.
    ///     sem.signal(1);
    ///     sem.acquire(1).await.unwrap();
    /// });
    /// ```
    pub fn signal(&self, units: u64) {
        process_wakes(self, units);
    }

    /// Closes the semaphore
    ///
    /// All existing waiters will return Err(), and no new waiters are allowed.
    ///
    /// # Examples
    ///
    /// ```
    /// use glommio::{sync::Semaphore, LocalExecutor};
    ///
    /// let sem = Semaphore::new(0);
    ///
    /// let ex = LocalExecutor::default();
    /// ex.run(async move {
    ///     // Note that we can signal to expand to more units than the original capacity had.
    ///     sem.close();
    ///     if let Ok(_) = sem.acquire(1).await {
    ///         panic!("a closed semaphore should have errored");
    ///     }
    /// });
    /// ```
    pub fn close(&self) {
        let mut state = self.state.borrow_mut();
        state.close();
    }
}

impl Drop for Semaphore {
    fn drop(&mut self) {
        assert!(self.state.borrow().waiters_list.is_empty());
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{
        enclose,
        timer::{sleep, Timer},
        Local,
        LocalExecutor,
    };

    use futures_lite::future::or;
    use std::{
        cell::Cell,
        rc::Rc,
        time::{Duration, Instant},
    };

    #[test]
    fn semaphore_acquisition_for_zero_unit_works() {
        make_shared_var!(Semaphore::new(1), sem1);

        test_executor!(async move {
            sem1.acquire(0).await.unwrap();
        });
    }

    #[test]
    fn permit_raii_works() {
        test_executor!(async move {
            let sem = Rc::new(Semaphore::new(0));
            let exec = Rc::new(Cell::new(0));

            let t1 = Local::local(enclose! { (sem, exec) async move {
                exec.set(exec.get() + 1);
                let _g = sem.acquire_permit(1).await.unwrap();
            }});
            let t2 = Task::local(enclose! { (sem, exec) async move {
                exec.set(exec.get() + 1);
                let _g = sem.acquire_permit(1).await.unwrap();
            }});

            // For this last one, use the static version. Move around and sleep a bit first
            let t3 = Local::local(enclose! { (sem, exec) async move {
                exec.set(exec.get() + 1);
                let g = sem.acquire_static_permit(1).await.unwrap();
                Local::local(async move {
                    let _g = g;
                    sleep(Duration::from_secs(1)).await;
                }).await
            }});

            // Wait for all permits to try and acquire, then unleash the gates.
            while exec.get() != 3 {
                Local::later().await;
            }
            sem.signal(1);

            t3.await;
            t2.await;
            t1.await;
            sleep(Duration::from_secs(2)).await;
            assert_eq!(sem.available(), 1);
        });
    }

    #[test]
    fn explicit_signal_unblocks_waiting_semaphore() {
        make_shared_var!(Semaphore::new(0), sem1, sem2);
        make_shared_var_mut!(0, exec1, exec2);

        test_executor!(
            async move {
                {
                    wait_on_cond!(exec1, 1);
                    let _g = sem1.acquire_permit(1).await.unwrap();
                    update_cond!(exec1, 2);
                }
            },
            async move {
                update_cond!(exec2, 1);
                let _ = sem2.signal(1);
                wait_on_cond!(exec2, 2, 1);
            }
        );
    }

    #[test]
    fn explicit_signal_unblocks_many_wakers() {
        make_shared_var!(Semaphore::new(0), sem1, sem2, sem3);

        test_executor!(
            async move {
                sem1.acquire(1).await.unwrap();
            },
            async move {
                sem2.acquire(1).await.unwrap();
            },
            async move {
                sem3.signal(2);
            }
        );
    }

    #[test]
    fn broken_semaphore_returns_the_right_error() {
        test_executor!(async move {
            let sem = Semaphore::new(0);
            sem.close();
            match sem.acquire(0).await {
                Ok(_) => panic!("Should have failed"),
                Err(e) => match e {
                    GlommioError::Closed(ResourceType::Semaphore { .. }) => {}
                    _ => panic!("Wrong Error"),
                },
            }
        });
    }

    #[test]
    fn try_acquire_sufficient_units() {
        let sem = Semaphore::new(42);
        assert!(sem.try_acquire(24).unwrap());
    }

    #[test]
    fn try_acquire_permit_sufficient_units() {
        let sem = Semaphore::new(42);
        let _ = sem.try_acquire_permit(24).unwrap();
    }

    #[test]
    fn try_acquire_insufficient_units() {
        let sem = Semaphore::new(42);
        assert!(!sem.try_acquire(62).unwrap());
    }

    #[test]
    fn try_acquire_permit_insufficient_units() {
        let sem = Semaphore::new(42);
        let result = sem.try_acquire_permit(62);
        assert!(result.is_err());

        let err = result.err().unwrap();
        if !matches!(
            err,
            GlommioError::WouldBlock(ResourceType::Semaphore { .. })
        ) {
            panic!("Incorrect error type is returned from try_acquire_permit method");
        }
    }

    #[test]
    fn try_acquire_semaphore_is_closed() {
        let sem = Semaphore::new(42);
        sem.close();

        let result = sem.try_acquire(24);
        assert!(result.is_err());

        let err = result.err().unwrap();
        if !matches!(err, GlommioError::Closed(ResourceType::Semaphore { .. })) {
            panic!("Incorrect error type is returned from try_acquire method");
        }
    }

    #[test]
    fn try_acquire_permit_semaphore_is_closed() {
        let sem = Semaphore::new(42);
        sem.close();

        let result = sem.try_acquire_permit(24);
        assert!(result.is_err());

        let err = result.err().unwrap();
        if !matches!(err, GlommioError::Closed(ResourceType::Semaphore { .. })) {
            panic!("Incorrect error type is returned from try_acquire_permit method");
        }
    }

    #[test]
    #[should_panic]
    fn broken_semaphore_if_close_happens_first() {
        make_shared_var!(Semaphore::new(1), sem1, sem2);
        make_shared_var_mut!(0, exec1, exec2);

        test_executor!(
            async move {
                wait_on_cond!(exec1, 1);
                // even if try to acquire 0, which always succeed,
                // we should fail if it is closed.
                let _g = sem1.acquire_permit(0).await.unwrap();
            },
            async move {
                sem2.close();
                update_cond!(exec2, 1);
            }
        );
    }

    #[test]
    #[should_panic]
    fn broken_semaphore_if_acquire_happens_first() {
        // Notice how in this test, for the acquire to happen first, we
        // need to block on the acquisition. So the semaphore starts at 0
        make_shared_var!(Semaphore::new(0), sem1, sem2);
        make_shared_var_mut!(0, exec1, exec2);

        test_executor!(
            async move {
                update_cond!(exec1, 1);
                let _g = sem1.acquire_permit(1).await.unwrap();
            },
            async move {
                wait_on_cond!(exec2, 1);
                sem2.close();
            }
        );
    }

    #[test]
    fn semaphore_overflow() {
        let ex = LocalExecutor::default();
        let semaphore = Rc::new(Semaphore::new(0));
        let semaphore_c = semaphore.clone();

        ex.run(async move {
            Local::local(async move {
                for _ in 0..100 {
                    Timer::new(Duration::from_micros(100)).await;
                }

                let mut waiters_count = 0;
                for _ in &semaphore_c.state.borrow().waiters_list {
                    waiters_count += 1;
                }

                assert_eq!(1, waiters_count);

                semaphore_c.signal(1);
            })
            .detach();

            let _ = semaphore.acquire(1).await.unwrap();
        });
    }

    #[test]
    fn semaphore_ensure_execution_order() {
        let ex = LocalExecutor::default();
        let semaphore = Rc::new(Semaphore::new(0));

        let semaphore_c1 = semaphore.clone();
        let semaphore_c2 = semaphore.clone();
        let semaphore_c3 = semaphore.clone();

        let state = Rc::new(RefCell::new(0));

        let state_c1 = state.clone();
        let state_c2 = state.clone();
        let state_c3 = state.clone();

        ex.run(async move {
            let t1 = Local::local(async move {
                *state_c1.borrow_mut() = 1;
                let _g = semaphore_c1.acquire_permit(1).await.unwrap();
                assert_eq!(*state_c1.borrow(), 3);
                *state_c1.borrow_mut() = 4;
            });

            let t2 = Local::local(async move {
                while *state_c2.borrow() != 1 {
                    Local::later().await;
                }

                *state_c2.borrow_mut() = 2;
                let _g = semaphore_c2.acquire_permit(1).await.unwrap();
                assert_eq!(*state_c2.borrow(), 4);
                *state_c2.borrow_mut() = 5;
            });

            let t3 = Local::local(async move {
                while *state_c3.borrow() != 2 {
                    Local::later().await;
                }

                *state_c3.borrow_mut() = 3;
                let _g = semaphore_c3.acquire_permit(1).await.unwrap();
                assert_eq!(*state_c3.borrow(), 5);
            });

            Local::local(async move {
                while *state.borrow() != 3 {
                    Local::later().await;
                }

                semaphore.signal(1);
            })
            .detach();

            or(or(t1, t2), t3).await;
        });
    }
}