sclass FastCollab is ICollab, AutoCloseable { settable bool useMainThread = true; volatile settable bool isDone; gettable int coresToUse; FastCollabWorker[] workers; AtomicReferenceArray workArray; // 0 = spin-wait, otherwise time to sleep in milliseconds settable int sleepTime = 0; settable PingSource interruptor = new; static final Runnable DONE = r { fail("Collab done") }; *(int coresToUse) { this.coresToUse = max(1, coresToUse); workArray = new AtomicReferenceArray(this.coresToUse); } public void addWork(Runnable work) { if (work == null) ret; for (int i = 0; i < workArray.length(); i++) if (workArray.compareAndSet(i, null, work)) ret; // Everyone is busy - do the work ourselves work.run(); } // returns null => sleep // returns DONE => all work done public Runnable grabWork(int workerIndex) { if (isDone) ret DONE; Runnable work = workArray.get(workerIndex); if (work != null) workArray.set(workerIndex, null); ret work; } public void done { isDone(true); } toString { ret "FastCollab*" + n2(coresToUse); } run { workers = new FastCollabWorker[coresToUse]; for i to coresToUse: workers[i] = new FastCollabWorker(this, i).interruptor(interruptor); int iFirst = useMainThread ? 1 : 0; for (int i = iFirst; i < coresToUse; i++) startThread(workers[i]); if (useMainThread) workers[0].run(); for (int i = iFirst; i < coresToUse; i++) workers[i].join(); } close { interruptor().cancel(); } }