2020-01-23 23:04:46 +03:00
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
2019-07-30 16:06:16 +03:00
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module sync
2020-05-10 08:58:54 +03:00
2019-12-22 01:41:42 +03:00
// [init_with=new_waitgroup] // TODO: implement support for init_with struct attribute, and disallow WaitGroup{} from outside the sync.new_waitgroup() function.
2020-05-10 08:58:54 +03:00
[ ref_only ]
2019-10-24 13:19:27 +03:00
pub struct WaitGroup {
2019-07-30 16:06:16 +03:00
mut :
2020-01-19 22:32:22 +03:00
mu & Mutex = & Mutex ( 0 )
2019-08-29 11:48:03 +03:00
active int
2019-07-30 16:06:16 +03:00
}
2020-01-19 22:32:22 +03:00
pub fn new_waitgroup ( ) & WaitGroup {
return & WaitGroup { mu : sync . new_mutex ( ) }
2019-10-25 17:24:40 +03:00
}
2019-07-30 16:06:16 +03:00
pub fn ( wg mut WaitGroup ) add ( delta int ) {
2019-08-29 11:48:03 +03:00
wg . mu . lock ( )
wg . active += delta
wg . mu . unlock ( )
if wg . active < 0 {
panic ( ' N e g a t i v e n u m b e r o f j o b s i n w a i t g r o u p ' )
}
2019-07-30 16:06:16 +03:00
}
pub fn ( wg mut WaitGroup ) done ( ) {
2019-08-29 11:48:03 +03:00
wg . add ( - 1 )
2019-07-30 16:06:16 +03:00
}
2019-12-06 19:23:24 +03:00
pub fn ( wg & WaitGroup ) wait ( ) {
2019-08-29 11:48:03 +03:00
for wg . active > 0 {
2019-12-03 15:05:08 +03:00
// Do not remove this, busy empty loops are optimized
// with -prod by some compilers, see issue #2874
$ if windows {
C . Sleep ( 1 )
} $ else {
C . usleep ( 1000 )
}
2019-08-29 11:48:03 +03:00
}
2019-07-30 16:06:16 +03:00
}
2019-12-22 01:41:42 +03:00