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

sync: add Once.do_with_param/2 method in addition to the existing Once.do/1 (workaround the absence of closures on windows)

This commit is contained in:
Delyan Angelov
2022-02-08 17:15:28 +02:00
parent 5d2995c4d5
commit dd835acb8d
2 changed files with 71 additions and 1 deletions

View File

@@ -16,7 +16,7 @@ pub fn new_once() &Once {
return once
}
// do execute the function only once.
// do executes the function `f()` only once
pub fn (mut o Once) do(f fn ()) {
if stdatomic.load_u64(&o.count) < 1 {
o.do_slow(f)
@@ -31,3 +31,34 @@ fn (mut o Once) do_slow(f fn ()) {
}
o.m.unlock()
}
// do_with_param executes `f(param)` only once`
// This method can be used as a workaround for passing closures to once.do/1 on Windows
// (they are not implemented there yet) - just pass your data explicitly.
// i.e. instead of:
// ```v
// once.do(fn [mut o] () {
// o.add(5)
// })
// ```
// ... you can use:
// ```v
// once.do_with_param(fn (mut o One) {
// o.add(5)
// }, o)
// ```
pub fn (mut o Once) do_with_param(f fn (voidptr), param voidptr) {
if stdatomic.load_u64(&o.count) < 1 {
o.do_slow_with_param(f, param)
}
}
fn (mut o Once) do_slow_with_param(f fn (p voidptr), param voidptr) {
o.m.@lock()
if o.count < 1 {
stdatomic.store_u64(&o.count, 1)
f(param)
}
o.m.unlock()
}