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.

1  
sclass FastCollab is ICollab, AutoCloseable {
2  
  settable bool useMainThread = true;
3  
  volatile settable bool isDone;
4  
  gettable int coresToUse;
5  
  FastCollabWorker[] workers;
6  
  AtomicReferenceArray<Runnable> workArray;
7  
  
8  
  // 0 = spin-wait, otherwise time to sleep in milliseconds
9  
  settable int sleepTime = 0;
10  
  
11  
  settable PingSource interruptor = new;
12  
  
13  
  static final Runnable DONE = r { fail("Collab done") };
14  
  
15  
  *(int coresToUse) {
16  
    this.coresToUse = max(1, coresToUse);
17  
    workArray = new AtomicReferenceArray(this.coresToUse);
18  
  }
19  
  
20  
  public void addWork(Runnable work) {
21  
    if (work == null) ret;
22  
    for (int i = 0; i < workArray.length(); i++)
23  
      if (workArray.compareAndSet(i, null, work))
24  
        ret;
25  
        
26  
    // Everyone is busy - do the work ourselves
27  
    work.run();
28  
  }
29  
  
30  
  // returns null => sleep
31  
  // returns DONE => all work done
32  
  public Runnable grabWork(int workerIndex) {
33  
    if (isDone) ret DONE;
34  
    Runnable work = workArray.get(workerIndex);
35  
    if (work != null)
36  
      workArray.set(workerIndex, null);
37  
    ret work;
38  
  }
39  
  
40  
  public void done { isDone(true); }
41  
  
42  
  toString { ret "FastCollab*" + n2(coresToUse); }
43  
  
44  
  run {
45  
    workers = new FastCollabWorker[coresToUse];
46  
    for i to coresToUse: 
47  
      workers[i] = new FastCollabWorker(this, i).interruptor(interruptor);
48  
      
49  
    int iFirst = useMainThread ? 1 : 0; 
50  
    for (int i = iFirst; i < coresToUse; i++)
51  
      startThread(workers[i]);
52  
    if (useMainThread)
53  
      workers[0].run();
54  
    for (int i = iFirst; i < coresToUse; i++)
55  
      workers[i].join();
56  
  }
57  
  
58  
  close {
59  
    interruptor().cancel();
60  
  }
61  
}

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: 169 / 292
Version history: 14 change(s)
Referenced in: [show references]