1 | sclass MultiThreadStepper implements AutoCloseable { |
2 | Runnable onDone; |
3 | Lock lock = lock(); |
4 | L<Thread> threads = synchroList(); |
5 | L<Steppable> steppables = synchroList(); |
6 | L<Steppable> stepping = synchroList(); |
7 | int cores = coresToUse(); |
8 | int idleDelay = 10; |
9 | volatile bool cancelled; |
10 | new AtomicLong steps; |
11 | long startTime; |
12 | volatile long elapsedTime; |
13 | |
14 | *() {} |
15 | *(Steppable... steppables) { addAll(this.steppables, steppables); } |
16 | *(Collection<? extends Steppable> steppables) { addAll(this.steppables, steppables); } |
17 | |
18 | void start { |
19 | print("Using " + n2(cores, "core")); |
20 | startTime = sysNow(); |
21 | repeat cores { |
22 | thread "Multi Thread Stepper" { |
23 | final Thread me = currentThread(); |
24 | threads.add(me); |
25 | afterwards { |
26 | bool done; |
27 | { |
28 | lock lock; |
29 | threads.remove(me); |
30 | done = empty(threads); |
31 | } |
32 | if (done) { |
33 | elapsedTime = sysNow()-startTime; |
34 | callF(onDone); |
35 | } |
36 | } |
37 | //int i = 0; |
38 | |
39 | while licensed { |
40 | Steppable s; |
41 | { |
42 | lock lock; |
43 | if (done()) ret; |
44 | //s = get(steppables, mod(i++, l(steppables))); |
45 | s = random(steppables); |
46 | if (s != null) { |
47 | steppables.remove(s); |
48 | stepping.add(s); |
49 | } |
50 | } |
51 | if (s == null) continue with sleep(idleDelay); |
52 | |
53 | bool done = false; |
54 | try { |
55 | incAtomicLong(steps); |
56 | done = !s.step(); |
57 | } catch e { |
58 | _handleException(e); |
59 | done = true; |
60 | } finally { |
61 | lock lock; |
62 | stepping.remove(s); |
63 | if (!done) steppables.add(s); |
64 | } |
65 | } |
66 | } |
67 | } |
68 | } |
69 | |
70 | bool done() { ret empty(steppables) || cancelled; } |
71 | |
72 | void stop { |
73 | cancelled = true; |
74 | cancelThreads(threads); |
75 | } |
76 | |
77 | void cleanMeUp { stop(); } |
78 | public void close() { stop(); } |
79 | |
80 | MultiThreadStepper onDone(Runnable r) { onDone = r; this; } |
81 | |
82 | void add(Steppable s) { steppables.add(s); } |
83 | |
84 | long steps() { ret steps!; } |
85 | } |
download show line numbers debug dex old transpilations
Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tvejysmllsmz, vouqrxazstgt
No comments. add comment
Snippet ID: | #1017897 |
Snippet name: | MultiThreadStepper |
Eternal ID of this version: | #1017897/10 |
Text MD5: | 9a38d3c5c0956723f28722a6e71eae8f |
Author: | stefan |
Category: | javax / execution |
Type: | JavaX fragment (include) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2018-10-09 16:46:36 |
Source code size: | 2213 bytes / 85 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 518 / 1068 |
Version history: | 9 change(s) |
Referenced in: | [show references] |