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

57
LINES

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

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

Libraryless. Click here for Pure Java version (9250L/51K).

sclass FastCollab is ICollab, AutoCloseable {
  settable bool useMainThread = true;
  volatile settable bool isDone;
  gettable int coresToUse;
  FastCollabWorker[] workers;
  AtomicReferenceArray<Runnable> workArray;
  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/13
Text MD5: 6ebbd8712227fffb7e28548e4703cf62
Transpilation MD5: 1305e035c3fb79e2ae930478531d9520
Author: stefan
Category: javax / parallelism
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-06-19 01:04:09
Source code size: 1576 bytes / 57 lines
Pitched / IR pitched: No / No
Views / Downloads: 35 / 111
Version history: 12 change(s)
Referenced in: [show references]