1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00
v/vlib/sync/waitgroup.v

44 lines
939 B
V
Raw Normal View History

2019-07-30 16:06:16 +03:00
// Copyright (c) 2019 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module sync
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.
pub struct WaitGroup {
2019-07-30 16:06:16 +03:00
mut:
2019-12-22 01:41:42 +03:00
mu Mutex
active int
2019-07-30 16:06:16 +03:00
}
2019-10-25 17:24:40 +03:00
pub fn new_waitgroup() WaitGroup {
2019-12-22 01:41:42 +03:00
mut w := WaitGroup{
}
2019-10-25 17:24:40 +03:00
w.mu = sync.new_mutex()
return w
}
2019-07-30 16:06:16 +03: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 16:06:16 +03:00
}
pub fn (wg mut WaitGroup) done() {
wg.add(-1)
2019-07-30 16:06:16 +03:00
}
2019-12-06 19:23:24 +03: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 16:06:16 +03:00
}
2019-12-22 01:41:42 +03:00