1 | module sync |
2 | |
3 | import sync.stdatomic |
4 | |
5 | pub struct ManyTimes { |
6 | mut: |
7 | m RwMutex |
8 | pub: |
9 | times u64 = 1 |
10 | count u64 |
11 | } |
12 | |
13 | // new_many_times return a new ManyTimes struct. |
14 | pub fn new_many_times(times u64) &ManyTimes { |
15 | mut many_times := &ManyTimes{ |
16 | times: times |
17 | } |
18 | many_times.m.init() |
19 | return many_times |
20 | } |
21 | |
22 | // do execute the function only setting times. |
23 | pub fn (mut m ManyTimes) do(f fn ()) { |
24 | if stdatomic.load_u64(&m.count) < m.times { |
25 | m.do_slow(f) |
26 | } |
27 | } |
28 | |
29 | fn (mut m ManyTimes) do_slow(f fn ()) { |
30 | m.m.@lock() |
31 | if m.count < m.times { |
32 | stdatomic.store_u64(&m.count, m.count + 1) |
33 | f() |
34 | } |
35 | m.m.unlock() |
36 | } |