Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

61
LINES

< > BotCompany Repo | #1035567 // FastCollab - code parallelizer using spin waits [OK]

JavaX fragment (include) [tags: use-pretranspiled]

Transpiled version (9250L) is out of date.

sclass FastCollab is ICollab, AutoCloseable {
  settable bool useMainThread = true;
  volatile settable bool isDone;
  gettable int coresToUse;
  FastCollabWorker[] workers;
  AtomicReferenceArray<Runnable> 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();
  }
}

Author comment

Began life as a copy of #1035564

download  show line numbers  debug dex  old transpilations   

Travelled to 3 computer(s): elmgxqgtpvxh, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

Snippet ID: #1035567
Snippet name: FastCollab - code parallelizer using spin waits [OK]
Eternal ID of this version: #1035567/15
Text MD5: b0dcc18999e567fcdb0152408410039f
Author: stefan
Category: javax / parallelism
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-11-03 19:51:58
Source code size: 1676 bytes / 61 lines
Pitched / IR pitched: No / No
Views / Downloads: 170 / 294
Version history: 14 change(s)
Referenced in: #1003674 - Standard Classes + Interfaces (LIVE continued in #1034167)