2021-12-05 17:56:03 +01:00
|
|
|
module sync
|
|
|
|
|
2021-12-28 09:12:40 +01:00
|
|
|
import sync.stdatomic
|
2021-12-05 17:56:03 +01:00
|
|
|
|
|
|
|
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 ()) {
|
2021-12-28 09:12:40 +01:00
|
|
|
if stdatomic.load_u64(&o.count) < 1 {
|
2021-12-05 17:56:03 +01:00
|
|
|
o.do_slow(f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn (mut o Once) do_slow(f fn ()) {
|
|
|
|
o.m.@lock()
|
|
|
|
if o.count < 1 {
|
2021-12-28 09:12:40 +01:00
|
|
|
stdatomic.store_u64(&o.count, 1)
|
2021-12-05 17:56:03 +01:00
|
|
|
f()
|
|
|
|
}
|
|
|
|
o.m.unlock()
|
|
|
|
}
|