Download Jar. Libraryless. Click here for Pure Java version (5864L/42K).
!7 sinterface Steppable { public bool step(); // return false if done } sclass MultiThreadStepper { Runnable onDone; Lock lock = lock(); L<Thread> threads = synchroList(); L<Steppable> steppables = synchroList(); L<Steppable> stepping = synchroList(); int coresToUse = coresToUse(); volatile bool cancelled; *() {} *(Steppable... steppables) { addAll(this.steppables, steppables); } *(Collection<? extends Steppable> steppables) { addAll(this.steppables, steppables); } void start { print("Using " + n2(coresToUse, "core")); repeat coresToUse { thread "Multi Thread Stepper" { final Thread me = currentThread(); threads.add(me); afterwards { bool done; { lock lock; threads.remove(me); done = empty(threads); } if (done) callF(onDone); } //int i = 0; while licensed { Steppable s; { lock lock; if (done()) ret; //s = get(steppables, mod(i++, l(steppables))); s = random(steppables); if (s == null) continue with sleep(100); steppables.remove(s); stepping.add(s); } bool done = false; try { done = !s.step(); } catch e { _handleException(e); done = true; } finally { lock lock; stepping.remove(s); if (!done) steppables.add(s); } } } } } bool done() { ret empty(steppables) || cancelled; } void stop { cancelled = true; cancelThreads(threads); } void cleanMeUp { stop(); } MultiThreadStepper onDone(Runnable r) { onDone = r; this; } } static noeq record MySteppable(int n) implements Steppable { int count = 0; public bool step() { if (count++ < 10) { print("Stepping: " + n); sleep(900+random(100)); true; } print("Steppable " + n + " done"); false; } } p-exp { new MultiThreadStepper(map(iota(10), func(int i) { MySteppable(i) })).onDone(rPrint("Done!")).start(); }
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: | #1017894 |
Snippet name: | Step in multiple threads Spike [OK] |
Eternal ID of this version: | #1017894/17 |
Text MD5: | 76aebeae2f5c1c8c25203940e5e7f506 |
Transpilation MD5: | 459d05df6f43172e5b73c568abd6b98e |
Author: | stefan |
Category: | javax / execution |
Type: | JavaX source code (desktop) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2018-08-19 13:38:15 |
Source code size: | 2281 bytes / 95 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 518 / 1097 |
Version history: | 16 change(s) |
Referenced in: | -