2021-12-05 18:44:25 +01:00
|
|
|
module sync
|
|
|
|
|
2021-12-28 09:12:40 +01:00
|
|
|
import sync.stdatomic
|
2021-12-05 18:44:25 +01:00
|
|
|
|
|
|
|
pub struct ManyTimes {
|
|
|
|
mut:
|
|
|
|
m RwMutex
|
|
|
|
pub:
|
|
|
|
times u64 = 1
|
|
|
|
count u64
|
|
|
|
}
|
|
|
|
|
|
|
|
// new_many_times return a new ManyTimes struct.
|
|
|
|
pub fn new_many_times(times u64) &ManyTimes {
|
|
|
|
mut many_times := &ManyTimes{
|
|
|
|
times: times
|
|
|
|
}
|
|
|
|
many_times.m.init()
|
|
|
|
return many_times
|
|
|
|
}
|
|
|
|
|
|
|
|
// do execute the function only setting times.
|
|
|
|
pub fn (mut m ManyTimes) do(f fn ()) {
|
2021-12-28 09:12:40 +01:00
|
|
|
if stdatomic.load_u64(&m.count) < m.times {
|
2021-12-05 18:44:25 +01:00
|
|
|
m.do_slow(f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn (mut m ManyTimes) do_slow(f fn ()) {
|
|
|
|
m.m.@lock()
|
|
|
|
if m.count < m.times {
|
2021-12-28 09:12:40 +01:00
|
|
|
stdatomic.store_u64(&m.count, m.count + 1)
|
2021-12-05 18:44:25 +01:00
|
|
|
f()
|
|
|
|
}
|
|
|
|
m.m.unlock()
|
|
|
|
}
|