mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
sync.once: add Once (#12722)
This commit is contained in:
33
vlib/sync/once.v
Normal file
33
vlib/sync/once.v
Normal file
@@ -0,0 +1,33 @@
|
||||
module sync
|
||||
|
||||
import sync.atomic2
|
||||
|
||||
pub struct Once {
|
||||
mut:
|
||||
m RwMutex
|
||||
pub:
|
||||
count u64
|
||||
}
|
||||
|
||||
// new_once return a new Once struct.
|
||||
pub fn new_once() &Once {
|
||||
mut once := &Once{}
|
||||
once.m.init()
|
||||
return once
|
||||
}
|
||||
|
||||
// do execute the function only once.
|
||||
pub fn (mut o Once) do(f fn ()) {
|
||||
if atomic2.load_u64(&o.count) < 1 {
|
||||
o.do_slow(f)
|
||||
}
|
||||
}
|
||||
|
||||
fn (mut o Once) do_slow(f fn ()) {
|
||||
o.m.@lock()
|
||||
if o.count < 1 {
|
||||
atomic2.store_u64(&o.count, 1)
|
||||
f()
|
||||
}
|
||||
o.m.unlock()
|
||||
}
|
||||
Reference in New Issue
Block a user