File tree 1 file changed +19
-5
lines changed
1 file changed +19
-5
lines changed Original file line number Diff line number Diff line change @@ -558,18 +558,23 @@ impl Drop for GroupGuard {
558
558
}
559
559
}
560
560
561
- #[ allow( dead_code) ]
562
- struct Once {
561
+ /// A predicate used to execute a closure only once for the lifetime of an
562
+ /// application.
563
+ pub struct Once {
563
564
predicate : UnsafeCell < dispatch_once_t > ,
564
565
}
565
566
566
- #[ allow( dead_code) ]
567
567
impl Once {
568
- // TODO: make this a const fn when the feature is stable
569
- pub fn new ( ) -> Once {
568
+ /// Creates a new `Once`.
569
+ pub const fn new ( ) -> Once {
570
570
Once { predicate : UnsafeCell :: new ( 0 ) }
571
571
}
572
572
573
+ /// Executes a closure once, ensuring that no other closure has been or
574
+ /// will be executed by self for the lifetype of the application.
575
+ ///
576
+ /// If called simultaneously from multiple threads, waits synchronously
577
+ // until the work has completed.
573
578
#[ inline( always) ]
574
579
pub fn call_once < F > ( & ' static self , work : F ) where F : FnOnce ( ) {
575
580
#[ cold]
@@ -799,4 +804,13 @@ mod tests {
799
804
// The notify must have run after the two blocks of the group
800
805
assert_eq ! ( * num. lock( ) . unwrap( ) , 10 ) ;
801
806
}
807
+
808
+ #[ test]
809
+ fn test_once ( ) {
810
+ static ONCE : Once = Once :: new ( ) ;
811
+ let mut num = 0 ;
812
+ ONCE . call_once ( || num += 1 ) ;
813
+ ONCE . call_once ( || num += 1 ) ;
814
+ assert ! ( num == 1 ) ;
815
+ }
802
816
}
You can’t perform that action at this time.
0 commit comments