v/vlib/sync/waitgroup.v

43 lines
953 B
V
Raw Normal View History

2020-01-23 21:04:46 +01:00
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
2019-07-30 15:06:16 +02:00
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module sync
2019-12-21 23:41:42 +01:00
// [init_with=new_waitgroup] // TODO: implement support for init_with struct attribute, and disallow WaitGroup{} from outside the sync.new_waitgroup() function.
[ref_only]
pub struct WaitGroup {
2019-07-30 15:06:16 +02:00
mut:
mu &Mutex = &Mutex(0)
active int
2019-07-30 15:06:16 +02:00
}
pub fn new_waitgroup() &WaitGroup {
return &WaitGroup{mu: sync.new_mutex() }
2019-10-25 16:24:40 +02:00
}
2019-07-30 15:06:16 +02:00
pub fn (wg mut WaitGroup) add(delta int) {
wg.mu.lock()
wg.active += delta
wg.mu.unlock()
if wg.active < 0 {
panic('Negative number of jobs in waitgroup')
}
2019-07-30 15:06:16 +02:00
}
pub fn (wg mut WaitGroup) done() {
wg.add(-1)
2019-07-30 15:06:16 +02:00
}
2019-12-06 17:23:24 +01:00
pub fn (wg &WaitGroup) wait() {
for wg.active > 0 {
// 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-07-30 15:06:16 +02:00
}
2019-12-21 23:41:42 +01:00