-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathexecution.html
More file actions
2115 lines (2009 loc) · 98.1 KB
/
Copy pathexecution.html
File metadata and controls
2115 lines (2009 loc) · 98.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Sync Node Flow Simulator v6</title>
<style>
:root {
color-scheme: light dark;
--bg: #0f1117;
--panel: #171b24;
--panel2: #1f2531;
--text: #edf2ff;
--muted: #a8b3c7;
--line: #323b4e;
--accent: #8fb8ff;
--mutex: #b99cff;
--sem: #ffd166;
--thread: #8bd3ff;
--cond: #7ee7c8;
--barrier: #f59ee0;
--sched: #f0a96a;
--good: #83d99a;
--warn: #ffd166;
--bad: #ff7b7b;
--node: #202839;
--node-border: #4b5875;
--shadow: rgba(0,0,0,.28);
--token: #e9eefc;
--token-text: #121722;
}
@media (prefers-color-scheme: light) {
:root {
--bg: #f6f8fc;
--panel: #ffffff;
--panel2: #eef2f8;
--text: #172033;
--muted: #63718a;
--line: #d6ddea;
--accent: #2867d8;
--mutex: #7b5ed8;
--sem: #b88700;
--thread: #0f83b8;
--cond: #008a68;
--barrier: #bd4aa3;
--sched: #c46b13;
--node: #ffffff;
--node-border: #aebbd2;
--shadow: rgba(20,38,72,.12);
--token: #172033;
--token-text: #ffffff;
}
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: var(--bg);
color: var(--text);
overflow: hidden;
}
header {
height: 50px;
display: flex;
align-items: center;
gap: 14px;
padding: 0 16px;
border-bottom: 1px solid var(--line);
background: var(--panel);
box-shadow: 0 1px 8px var(--shadow);
position: relative;
z-index: 4;
}
header h1 { font-size: 16px; margin: 0; letter-spacing: .2px; white-space: nowrap; }
header .hint { color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
#app {
height: 100%;
display: grid;
grid-template-columns: 278px minmax(360px, 1fr) 336px;
min-width: 0;
transition: grid-template-columns .18s ease;
}
#app.hide-left { grid-template-columns: 0 minmax(360px, 1fr) 336px; }
#app.hide-right { grid-template-columns: 278px minmax(360px, 1fr) 0; }
#app.hide-left.hide-right { grid-template-columns: 0 minmax(360px, 1fr) 0; }
aside {
background: var(--panel);
border-right: 1px solid var(--line);
overflow: auto;
padding: 12px;
min-width: 0;
transition: padding .18s ease, border-color .18s ease;
}
aside.right { border-right: 0; border-left: 1px solid var(--line); }
#app.hide-left aside.left, #app.hide-right aside.right { padding: 0; border-color: transparent; overflow: hidden; }
#app.hide-left aside.left > *, #app.hide-right aside.right > * { display: none; }
section {
background: var(--panel2);
border: 1px solid var(--line);
border-radius: 14px;
padding: 10px;
margin-bottom: 12px;
box-shadow: 0 6px 18px var(--shadow);
}
h2, h3 { margin: 0 0 8px; font-size: 13px; }
p, li, small { color: var(--muted); line-height: 1.35; }
small { display: block; font-size: 11px; }
.row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
button, select, input, textarea {
font: inherit;
border: 1px solid var(--line);
border-radius: 10px;
background: var(--panel);
color: var(--text);
padding: 7px 9px;
outline: none;
}
button { cursor: pointer; user-select: none; transition: transform .05s ease, border-color .15s ease, background .15s ease; }
button:hover { border-color: var(--accent); }
button:active { transform: translateY(1px); }
button.primary { background: color-mix(in srgb, var(--accent) 25%, var(--panel)); border-color: var(--accent); }
button.danger { color: var(--bad); }
button.active { border-color: var(--warn); box-shadow: inset 0 0 0 1px var(--warn); }
button:disabled { opacity: .45; cursor: not-allowed; }
.btn-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 7px; }
.btn-grid button { text-align: left; font-size: 12px; }
.palette button { position: relative; overflow: hidden; }
.palette button::before { content: ''; position: absolute; inset: 0 auto 0 0; width: 5px; background: var(--accent); opacity: .95; }
.palette button[data-add="lock"]::before, .palette button[data-add="unlock"]::before { background: var(--mutex); }
.palette button[data-add="sem_wait"]::before, .palette button[data-add="sem_post"]::before { background: var(--sem); }
.palette button[data-add="spawn"]::before, .palette button[data-add="join"]::before { background: var(--thread); }
.palette button[data-add="cond_wait"]::before, .palette button[data-add="cond_signal"]::before, .palette button[data-add="cond_broadcast"]::before { background: var(--cond); }
.palette button[data-add="barrier"]::before { background: var(--barrier); }
.palette button[data-add="yield"]::before, .palette button[data-add="park"]::before { background: var(--sched); }
.palette button[data-add="work"]::before { background: var(--good); }
.palette button[data-add="end"]::before { background: var(--bad); }
.wide { width: 100%; }
.control-stack { display: grid; grid-template-columns: 1fr 1fr; gap: 7px; }
label { color: var(--muted); font-size: 11px; display: block; margin-bottom: 4px; }
input, textarea, select { width: 100%; font-size: 12px; }
textarea { min-height: 86px; resize: vertical; }
main { position: relative; overflow: hidden; }
#toolbar {
position: absolute;
z-index: 3;
top: 12px;
left: 12px;
display: flex;
gap: 8px;
align-items: center;
background: color-mix(in srgb, var(--panel) 93%, transparent);
border: 1px solid var(--line);
border-radius: 14px;
padding: 8px;
box-shadow: 0 6px 20px var(--shadow);
backdrop-filter: blur(8px);
}
#canvasWrap {
position: absolute;
inset: 0;
overflow: hidden;
background-image:
linear-gradient(var(--line) 1px, transparent 1px),
linear-gradient(90deg, var(--line) 1px, transparent 1px);
background-size: 32px 32px;
background-position: -1px -1px;
}
#edges { position: absolute; inset: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1; }
#nodesLayer { position: absolute; inset: 0; z-index: 2; }
.node {
position: absolute;
width: 144px;
min-height: 66px;
border: 1px solid var(--node-border);
border-radius: 14px;
background: var(--node);
color: var(--text);
box-shadow: 0 10px 24px var(--shadow);
cursor: grab;
user-select: none;
overflow: hidden;
}
.node:active { cursor: grabbing; }
.node.selected { border-color: var(--accent); box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 45%, transparent), 0 10px 24px var(--shadow); }
.node.wire-source { border-color: var(--warn); box-shadow: 0 0 0 2px color-mix(in srgb, var(--warn) 45%, transparent); }
.node .top { display: flex; align-items: center; gap: 7px; padding: 8px 9px 5px; }
.pill { width: 9px; height: 9px; border-radius: 99px; background: var(--accent); flex: 0 0 auto; }
.node.start .pill { background: var(--good); }
.node.end .pill { background: var(--bad); }
.node.mutex .pill { background: var(--mutex); }
.node.sem .pill { background: var(--sem); }
.node.work .pill { background: var(--good); }
.node.spawn .pill, .node.join .pill { background: var(--thread); }
.node.cond .pill { background: var(--cond); }
.node.barrier .pill { background: var(--barrier); }
.node.sched .pill { background: var(--sched); }
.node .title { font-size: 12px; font-weight: 750; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.node .sub { color: var(--muted); font-size: 10.5px; padding: 0 9px 8px; min-height: 15px; }
.tokens { display: flex; gap: 4px; flex-wrap: wrap; padding: 0 8px 8px; min-height: 22px; }
.token { border-radius: 999px; padding: 2px 6px; background: var(--token); color: var(--token-text); font-size: 10px; font-weight: 800; letter-spacing: .2px; }
.token.blocked { background: var(--warn); color: #2b2100; }
.token.done { background: var(--good); color: #06210d; }
.token.error { background: var(--bad); color: #260000; }
.mini-list { display: grid; gap: 6px; }
.token-row, .state-row, .ap-row {
display: grid;
grid-template-columns: auto 1fr auto;
gap: 8px;
align-items: center;
padding: 7px;
border: 1px solid var(--line);
border-radius: 10px;
background: var(--panel);
font-size: 12px;
}
.ap-row { grid-template-columns: 34px 1fr; }
.token-row.selected { border-color: var(--accent); }
.token-name { font-weight: 800; }
.token-place, .state-detail { color: var(--muted); font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.status { font-size: 10px; border-radius: 999px; padding: 2px 6px; background: var(--panel2); border: 1px solid var(--line); white-space: nowrap; }
.status.ready { color: var(--good); }
.status.blocked { color: var(--warn); }
.status.done { color: var(--muted); }
.status.error { color: var(--bad); }
#log { max-height: 260px; overflow: auto; display: flex; flex-direction: column-reverse; gap: 6px; font-size: 12px; }
.log-item { padding: 7px 8px; border: 1px solid var(--line); border-radius: 10px; background: var(--panel); color: var(--muted); line-height: 1.3; }
.log-item strong { color: var(--text); }
.log-item.warn { border-color: color-mix(in srgb, var(--warn) 45%, var(--line)); color: var(--warn); }
.log-item.bad { border-color: color-mix(in srgb, var(--bad) 50%, var(--line)); color: var(--bad); }
.log-item.good { border-color: color-mix(in srgb, var(--good) 45%, var(--line)); color: var(--good); }
.concept { display: grid; gap: 7px; }
.concept code { background: var(--panel); border: 1px solid var(--line); border-radius: 7px; padding: 1px 5px; color: var(--text); }
.legend { display: grid; gap: 6px; font-size: 12px; color: var(--muted); }
.legend span { display: flex; gap: 7px; align-items: center; }
.legend b { color: var(--text); }
.dot { width: 10px; height: 10px; border-radius: 50%; background: var(--accent); display: inline-block; flex: 0 0 auto; }
.dot.m { background: var(--mutex); } .dot.s { background: var(--sem); } .dot.c { background: var(--good); } .dot.t { background: var(--thread); } .dot.v { background: var(--cond); } .dot.b { background: var(--barrier); } .dot.y { background: var(--sched); }
.split { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.muted { color: var(--muted); }
.kbd { border: 1px solid var(--line); border-bottom-width: 2px; border-radius: 6px; padding: 0 5px; background: var(--panel); color: var(--text); font-size: 11px; }
.thin { font-size: 11px; padding: 5px 7px; }
.node-progress { display: flex; gap: 4px; flex-wrap: wrap; padding: 0 8px 8px; min-height: 16px; }
.progress-chip { font-size: 10px; border: 1px solid var(--line); border-radius: 999px; padding: 1px 6px; background: var(--panel2); color: var(--warn); font-weight: 800; }
.deadlock-badge {
position: absolute;
z-index: 5;
top: 58px;
left: 50%;
transform: translateX(-50%);
border: 1px solid color-mix(in srgb, var(--bad) 65%, var(--line));
background: color-mix(in srgb, var(--bad) 18%, var(--panel));
color: var(--bad);
border-radius: 999px;
padding: 7px 12px;
box-shadow: 0 8px 22px var(--shadow);
font-size: 12px;
font-weight: 850;
max-width: min(620px, 82%);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.panel-toggle {
position: absolute;
z-index: 4;
top: 12px;
border-radius: 999px;
padding: 6px 10px;
background: color-mix(in srgb, var(--panel) 93%, transparent);
box-shadow: 0 6px 20px var(--shadow);
backdrop-filter: blur(8px);
font-size: 12px;
}
.panel-toggle.left { left: 12px; }
.panel-toggle.right { right: 12px; }
#toolbar { left: 50%; transform: translateX(-50%); }
</style>
</head>
<body>
<div id="app">
<aside class="left">
<section>
<h3>Examples</h3>
<div class="btn-grid">
<button data-example="race">Race: no mutex</button>
<button data-example="rr">RR: 1 AP, 3 threads</button>
<button data-example="mutex">Mutex protects inc</button>
<button data-example="semSeats">Semaphore seats</button>
<button data-example="semSignal">Semaphore signal</button>
<button data-example="barrier">Barrier B</button>
<button data-example="spawnJoin">Spawn + join</button>
<button data-example="yieldPark">Yield / park</button>
<button data-example="atomicInc">Atomic inc</button>
<button data-example="condSignal">Condvar signal</button>
<button data-example="condBroadcast">CV broadcast</button>
<button data-example="condLost">CV lost signal</button>
<button data-example="selfDeadlock">Self-deadlock</button>
<button data-example="badUnlock">Bad unlock</button>
</div>
<small style="margin-top:8px">Try <b>Race</b>, then <b>RR</b>: with 1 AP and 3 threads, round-robin still makes every token progress.</small>
</section>
<section>
<h3>AP / CPU slots</h3>
<div class="split">
<div>
<label for="apCount">AP count</label>
<input id="apCount" type="number" min="1" max="8" step="1" value="2" />
</div>
<div>
<label> </label>
<button id="applyAPBtn" class="primary wide">Apply</button>
</div>
</div>
<div id="apList" class="mini-list" style="margin-top:8px"></div>
<div class="row" style="margin-top:8px">
<button id="makeStartsBtn" class="wide">Make one Start per AP slot</button>
</div>
<div style="margin-top:8px">
<label for="lensSelect">Interpretation lens</label>
<select id="lensSelect">
<option value="threads">Plain threads</option>
<option value="tokio">Tokio workers/tasks</option>
<option value="rayon">Rayon workers/jobs</option>
</select>
</div>
<small style="margin-top:8px">APs are CPU slots. Start nodes spawn tokens; the round-robin scheduler dispatches up to AP count tokens per SMP tick. The lens only changes how you read the same graph.</small>
</section>
<section>
<h3>Add node</h3>
<div class="btn-grid palette">
<button data-add="start">Start</button>
<button data-add="work">Work</button>
<button data-add="lock">Lock M</button>
<button data-add="unlock">Unlock M</button>
<button data-add="sem_wait">Wait S</button>
<button data-add="sem_post">Post S</button>
<button data-add="yield">Yield</button>
<button data-add="park">Park N</button>
<button data-add="spawn">Spawn T</button>
<button data-add="join">Join T</button>
<button data-add="cond_wait">Wait C/M</button>
<button data-add="cond_signal">Signal C</button>
<button data-add="cond_broadcast">Broadcast C</button>
<button data-add="barrier">Barrier B</button>
<button data-add="end">End</button>
</div>
<div class="row" style="margin-top:8px">
<button id="wireBtn" class="wide">Wire mode: off</button>
<button id="deleteBtn" class="danger wide">Delete selected</button>
</div>
<small style="margin-top:8px">Drag nodes. In wire mode, click source → target. Press <span class="kbd">Tab</span> to toggle move/wire. Most sources have one outgoing edge; Spawn has a normal parent edge plus a dashed child edge. Shift-click the target while wiring from Spawn to set the child edge. Any node, including End, may have many incoming edges.</small>
</section>
<section>
<h3>Simulation</h3>
<div style="margin-bottom:8px">
<label for="selectedTokenSelect">Selected thread for debug step</label>
<select id="selectedTokenSelect"></select>
</div>
<div class="control-stack">
<button id="resetBtn" class="primary">Reset</button>
<button id="stepNextBtn">SMP tick</button>
<button id="stepSelectedBtn">Step selected thread</button>
<button id="runBtn">Run SMP</button>
</div>
<div class="split" style="margin-top:8px">
<div>
<label for="semInit">Default S permits</label>
<input id="semInit" type="number" min="0" max="99" step="1" value="1" />
</div>
<div>
<label for="runSpeed">Run delay ms</label>
<input id="runSpeed" type="number" min="120" max="2000" step="50" value="650" />
</div>
</div>
<small style="margin-top:8px"><b>SMP tick</b> round-robin dispatches up to AP-count ready tokens. <b>Step selected</b> is a debugger micro-step for one token only. <b>Default S permits</b>: 0 = event/signal, 1 = binary semaphore, N = N seats/resources.</small>
</section>
<section>
<h3>Threads</h3>
<div id="tokens" class="mini-list"></div>
</section>
<section>
<h3>Selected node</h3>
<div id="selectedPanel" class="concept"></div>
</section>
</aside>
<main>
<button id="toggleLeftPanel" class="panel-toggle left">Hide left</button>
<button id="toggleRightPanel" class="panel-toggle right">Hide right</button>
<div id="deadlockBadge" class="deadlock-badge" hidden>Deadlock</div>
<div id="toolbar">
<span class="muted">Tool:</span>
<button id="moveTool" class="active">Move</button>
<button id="wireTool">Wire</button>
<span id="wireHint" class="muted">click source → target</span>
</div>
<div id="canvasWrap">
<svg id="edges" aria-hidden="true"></svg>
<div id="nodesLayer"></div>
</div>
</main>
<aside class="right">
<section>
<h3>Shared state</h3>
<div id="state" class="mini-list"></div>
</section>
<section>
<div class="row" style="justify-content:space-between; margin-bottom:8px">
<h3 style="margin:0">Event log</h3>
<button id="clearLogBtn">Clear</button>
</div>
<div id="log"></div>
</section>
<section>
<h3>Tiny model</h3>
<div class="concept">
<div id="lensHelp"></div>
<small><b>Mutex</b>: one owner or free. If busy, lockers queue. Only the owner may unlock.</small>
<small><b>Semaphore</b>: integer permits. <code>wait</code> consumes one or blocks. <code>post</code> wakes one waiter or adds a permit. No owner.</small>
<small><b>Spawn / Join</b>: Spawn creates a child thread on its dashed child edge; the parent follows the normal edge. Join waits for a child handle from the same parent.</small>
<small><b>Condition variable</b>: <code>Wait C/M</code> requires owning mutex M, atomically unlocks M and sleeps on C. Signal wakes one waiter; Broadcast wakes all. Woken waiters must re-lock M before continuing.</small>
<small><b>Barrier</b>: N tokens must arrive at the same barrier generation before all are released together.</small>
<small><b>Yield</b>: cooperative scheduling point. The token advances, but visually marks a place where a Tokio task would give the worker back to the runtime.</small>
<small><b>Park N</b>: token becomes not-ready until a future scheduler tick. Read it as sleep/timer/awaited event; it does not consume an AP slot while parked.</small>
<small><b>SMP tick</b>: a round-robin scheduler chooses up to AP-count ready tokens from a start-of-tick snapshot. Lock/semaphore conflicts are resolved in dispatch order.</small>
<small><b>Work node</b>: can take N scheduled micro-steps per thread. Scenario <code>increment counter</code> is non-atomic: first step reads, final step writes. Each token shows per-node progress like 1/3.</small>
</div>
</section>
<section>
<h3>Things to try</h3>
<div class="legend">
<span><i class="dot c"></i><b>Race:</b> press SMP tick until both APs read counter=0 in the same tick, then both write.</span>
<span><i class="dot m"></i><b>Mutex:</b> AP1 blocks while AP0 owns M.</span>
<span><i class="dot s"></i><b>Semaphore:</b> set default S permits to 1, 2, or 0 and reset.</span>
<span><i class="dot t"></i><b>Spawn/join:</b> normal edge is the parent; dashed edge is the child path.</span>
<span><i class="dot v"></i><b>Condvar:</b> try Signal before Wait to see that condition variables do not store permits.</span>
<span><i class="dot b"></i><b>Barrier:</b> lower AP count to see arrivals spread over scheduler ticks.</span>
<span><i class="dot y"></i><b>Yield/Park:</b> use Yield to mark cooperative handoff; use Park N to make a token sleep without occupying an AP slot.</span>
<span><i class="dot"></i><b>Work duration:</b> select a Work node and change Steps to 3 or 5.</span>
</div>
</section>
<section>
<h3>Graph JSON</h3>
<div class="control-stack">
<button id="exportBtn">Export</button>
<button id="importBtn">Import</button>
</div>
<textarea id="jsonBox" placeholder="Exported graph appears here"></textarea>
</section>
</aside>
</div>
<script>
(() => {
'use strict';
const $ = (sel, root = document) => root.querySelector(sel);
const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
const clamp = (v, lo, hi) => Math.max(lo, Math.min(hi, v));
const WORK_SCENARIOS = {
plain: { label: 'Plain work', sub: 'ordinary work' },
inc: { label: 'Increment counter', sub: 'read first, write last' },
atomicInc: { label: 'Atomic increment', sub: 'single indivisible counter++' },
readCounter: { label: 'Read counter to local', sub: 'local = counter' },
writeLocalPlusOne: { label: 'Write local + 1', sub: 'counter = local + 1' },
setCounter: { label: 'Set counter', sub: 'counter = value' }
};
const TYPE = {
start: { title: 'Start', cls: 'start', sub: n => `spawns ${n.ap === '*' ? 'one thread per AP slot' : 'thread ' + (n.ap || n.threadName || n.thread || 'T?')}` },
work: { title: 'Work', cls: 'work', sub: n => `${workScenario(n).label}, ${workSteps(n)} step${workSteps(n) === 1 ? '' : 's'}` },
lock: { title: 'Lock M', cls: 'mutex', sub: n => `mutex ${n.obj || 'M'}` },
unlock: { title: 'Unlock M', cls: 'mutex', sub: n => `mutex ${n.obj || 'M'}` },
sem_wait: { title: 'Wait S', cls: 'sem', sub: n => `semaphore ${n.obj || 'S'}: consume permit` },
sem_post: { title: 'Post S', cls: 'sem', sub: n => `semaphore ${n.obj || 'S'}: release/signal` },
yield: { title: 'Yield', cls: 'sched', sub: () => 'cooperative handoff point' },
park: { title: 'Park N', cls: 'sched', sub: n => `park ${parkTicks(n)} scheduler tick${parkTicks(n) === 1 ? '' : 's'}` },
spawn: { title: 'Spawn T', cls: 'spawn', sub: n => `spawn ${n.spawnName || 'T'} on dashed child edge` },
join: { title: 'Join T', cls: 'join', sub: n => `wait for child ${n.joinName || 'T'}` },
cond_wait: { title: 'Wait C/M', cls: 'cond', sub: n => `cond ${n.obj || 'C'} with mutex ${n.mutex || 'M'}` },
cond_signal: { title: 'Signal C', cls: 'cond', sub: n => `wake one waiter on cond ${n.obj || 'C'}` },
cond_broadcast: { title: 'Broadcast C', cls: 'cond', sub: n => `wake all waiters on cond ${n.obj || 'C'}` },
barrier: { title: 'Barrier B', cls: 'barrier', sub: n => `barrier ${n.obj || 'B'}: ${barrierParties(n)} parties` },
end: { title: 'End', cls: 'end', sub: () => 'finish token; many incoming ok' }
};
const els = {
edges: $('#edges'),
nodesLayer: $('#nodesLayer'),
canvasWrap: $('#canvasWrap'),
tokens: $('#tokens'),
state: $('#state'),
log: $('#log'),
selectedPanel: $('#selectedPanel'),
semInit: $('#semInit'),
runSpeed: $('#runSpeed'),
wireBtn: $('#wireBtn'),
wireTool: $('#wireTool'),
moveTool: $('#moveTool'),
wireHint: $('#wireHint'),
jsonBox: $('#jsonBox'),
apCount: $('#apCount'),
apList: $('#apList'),
lensSelect: $('#lensSelect'),
lensHelp: $('#lensHelp'),
selectedTokenSelect: $('#selectedTokenSelect')
};
let graph = emptyGraph();
let sim = emptySim();
let selectedNodeId = null;
let selectedTokenId = null;
let wireMode = false;
let wireSourceId = null;
let drag = null;
let idSeq = 1;
let runTimer = null;
let rr = 0;
function emptyGraph() {
return {
apCount: 2,
apNames: ['AP0', 'AP1'],
semInit: 1,
semDefaults: { S: 1 },
lens: 'threads',
nodes: [],
edges: []
};
}
function emptySim() {
return {
tick: 0,
micro: 0,
lastTickRan: [],
lastDispatch: [],
counter: 0,
mutexes: {},
semaphores: {},
condvars: {},
barriers: {},
children: {},
tokens: [],
log: [],
deadlock: false,
deadlockReason: '',
_stallLogged: false
};
}
function uid(prefix = 'n') { return `${prefix}${idSeq++}`; }
function byId(id) { return graph.nodes.find(n => n.id === id); }
function edgeKind(e) { return e?.kind === 'spawn' ? 'spawn' : 'normal'; }
function edgeFrom(id, kind = 'normal') { return graph.edges.find(e => e.from === id && edgeKind(e) === kind); }
function childEdgeFrom(id) { return edgeFrom(id, 'spawn'); }
function nextId(id) { const e = edgeFrom(id, 'normal'); return e ? e.to : null; }
function childNextId(id) { const e = childEdgeFrom(id); return e ? e.to : null; }
function outgoingIds(id) { return graph.edges.filter(e => e.from === id).map(e => e.to).filter(Boolean); }
function tokenById(id) { return sim.tokens.find(t => t.id === id); }
function nodeLabel(n) { return n ? (n.label || TYPE[n.type]?.title || n.type) : 'missing'; }
function queueText(q) { return q.length ? q.join(' → ') : 'empty'; }
function htmlEscape(s) {
return String(s ?? '').replace(/[&<>'"]/g, c => ({'&':'&','<':'<','>':'>',"'":''','"':'"'}[c]));
}
function sanitizeName(raw, fallback) {
const s = String(raw ?? '').trim();
return s || fallback;
}
function makeUnique(names) {
const seen = new Map();
return names.map((name, i) => {
let base = sanitizeName(name, `AP${i}`);
let candidate = base;
let n = seen.get(base) || 0;
while (seen.has(candidate)) {
n += 1;
candidate = `${base}_${n}`;
}
seen.set(base, n);
seen.set(candidate, 0);
return candidate;
});
}
function migrateGraph(g) {
const rawApCount = Number(g.apCount);
const hasApCount = Number.isFinite(rawApCount) && rawApCount > 0;
const next = {
apCount: hasApCount ? clamp(rawApCount, 1, 8) : 0,
apNames: Array.isArray(g.apNames) ? g.apNames.slice(0, 8) : [],
semInit: Number.isFinite(Number(g.semInit)) ? Number(g.semInit) : 1,
semDefaults: g.semDefaults && typeof g.semDefaults === 'object' ? {...g.semDefaults} : {},
lens: ['threads','tokio','rayon'].includes(g.lens) ? g.lens : 'threads',
nodes: Array.isArray(g.nodes) ? g.nodes.map(n => ({...n})) : [],
edges: Array.isArray(g.edges) ? g.edges.map(e => ({...e, kind: e.kind === 'spawn' ? 'spawn' : 'normal'})) : []
};
for (const n of next.nodes) {
if (n.type === 'inc') {
n.type = 'work';
n.workKind = 'inc';
n.steps = Math.max(2, Number(n.steps || 2));
n.label = n.label || 'Inc counter';
}
if (n.type === 'start' && !n.ap) n.ap = n.threadName || n.thread || undefined;
if (n.type === 'work') {
n.workKind = n.workKind || 'plain';
n.steps = Number.isFinite(Number(n.steps)) ? Number(n.steps) : (n.workKind === 'inc' ? 2 : 1);
}
if (n.type === 'park') n.ticks = parkTicks(n);
if (n.type === 'spawn') n.spawnName = sanitizeName(n.spawnName, 'T');
if (n.type === 'join') n.joinName = sanitizeName(n.joinName, 'T');
if (['cond_wait','cond_signal','cond_broadcast'].includes(n.type)) n.obj = sanitizeName(n.obj, 'C');
if (n.type === 'cond_wait') n.mutex = sanitizeName(n.mutex, 'M');
if (n.type === 'barrier') {
n.obj = sanitizeName(n.obj, 'B');
n.parties = clamp(Math.floor(Number(n.parties || next.apCount || 2)), 1, 64);
}
}
if (!next.apNames.length) {
next.apNames = ['AP0', 'AP1'];
}
if (!next.apCount) next.apCount = clamp(next.apNames.length || 2, 1, 8);
next.apCount = clamp(next.apCount, 1, 8);
while (next.apNames.length < next.apCount) next.apNames.push(`AP${next.apNames.length}`);
next.apNames = makeUnique(next.apNames.slice(0, next.apCount));
if (!Object.prototype.hasOwnProperty.call(next.semDefaults, 'S')) next.semDefaults.S = next.semInit;
return next;
}
function getRoster() {
graph = migrateGraph(graph);
return graph.apNames.slice(0, graph.apCount);
}
function workScenario(n) {
return WORK_SCENARIOS[n.workKind || 'plain'] || WORK_SCENARIOS.plain;
}
function workSteps(n) {
let steps = clamp(Math.floor(Number(n.steps || 1)), 1, 30);
if ((n.workKind || 'plain') === 'inc') steps = Math.max(2, steps);
return steps;
}
function semDefault(obj) {
if (!graph.semDefaults) graph.semDefaults = {};
if (Object.prototype.hasOwnProperty.call(graph.semDefaults, obj)) return Math.max(0, Number(graph.semDefaults[obj]) || 0);
return Math.max(0, Number(graph.semInit || 0));
}
function barrierParties(n) {
return clamp(Math.floor(Number(n?.parties || graph.apCount || 2)), 1, 64);
}
function parkTicks(n) {
return clamp(Math.floor(Number(n?.ticks || 2)), 1, 99);
}
function lensInfo() {
const lens = ['threads','tokio','rayon'].includes(graph.lens) ? graph.lens : 'threads';
if (lens === 'tokio') return { name: 'Tokio lens', slots: 'worker threads', tokens: 'tasks/futures', spawn: 'task spawn', join: 'JoinHandle await', yield: 'yield/.await point' };
if (lens === 'rayon') return { name: 'Rayon lens', slots: 'worker threads', tokens: 'jobs', spawn: 'fork/spawn job', join: 'join/scope wait', yield: 'scheduler yield point' };
return { name: 'Plain thread lens', slots: 'AP/CPU slots', tokens: 'thread tokens', spawn: 'thread spawn', join: 'thread join', yield: 'cooperative yield marker' };
}
function barrierKey(n) { return n?.id || String(n); }
function usedBarrierNodes() {
return graph.nodes.filter(n => n.type === 'barrier');
}
function uniqueTokenId(base) {
const clean = sanitizeName(base, 'T').replace(/\s+/g, '_');
const exists = name => sim.tokens.some(t => t.id === name);
if (!exists(clean)) return clean;
let i = 2;
while (exists(`${clean}_${i}`)) i += 1;
return `${clean}_${i}`;
}
function registerChild(parentId, alias, childId) {
if (!sim.children[parentId]) sim.children[parentId] = {};
const key = sanitizeName(alias, 'T');
if (!sim.children[parentId][key]) sim.children[parentId][key] = [];
sim.children[parentId][key].push(childId);
}
function childIdsFor(parentId, alias) {
const byAlias = sim.children[parentId] || {};
if (alias === '*') return Object.values(byAlias).flat();
return (byAlias[alias] || []).slice();
}
function isTerminalToken(t) { return !t || t.status === 'done' || t.status === 'error'; }
function childLabel(childIds) { return childIds.length ? childIds.join(', ') : 'none'; }
function usedMutexNames() {
const set = new Set(['M']);
for (const n of graph.nodes) {
if (['lock', 'unlock'].includes(n.type)) set.add(n.obj || 'M');
if (n.type === 'cond_wait') set.add(n.mutex || 'M');
}
return Array.from(set).sort();
}
function usedSemaphoreNames() {
const set = new Set(['S']);
for (const n of graph.nodes) if (['sem_wait', 'sem_post'].includes(n.type)) set.add(n.obj || 'S');
return Array.from(set).sort();
}
function usedCondNames() {
const set = new Set(['C']);
for (const n of graph.nodes) if (['cond_wait','cond_signal','cond_broadcast'].includes(n.type)) set.add(n.obj || 'C');
return Array.from(set).sort();
}
function addLog(message, kind = '') {
sim.log.push({ tick: sim.tick, message, kind });
if (sim.log.length > 160) sim.log.shift();
renderLog();
}
function renderLog() {
els.log.innerHTML = sim.log.map(item =>
`<div class="log-item ${item.kind}"><strong>#${item.tick}</strong> ${item.message}</div>`
).join('');
}
function ensureObjects() {
for (const name of usedMutexNames()) {
if (!sim.mutexes[name]) sim.mutexes[name] = { owner: null, queue: [] };
}
for (const name of usedSemaphoreNames()) {
if (!sim.semaphores[name]) sim.semaphores[name] = { count: semDefault(name), queue: [] };
}
for (const name of usedCondNames()) {
if (!sim.condvars[name]) sim.condvars[name] = { waiters: [] };
}
for (const n of usedBarrierNodes()) {
const key = barrierKey(n);
if (!sim.barriers[key]) sim.barriers[key] = { obj: n.obj || 'B', nodeId: n.id, parties: barrierParties(n), generation: 0, queue: [] };
sim.barriers[key].obj = n.obj || 'B';
sim.barriers[key].parties = barrierParties(n);
sim.barriers[key].nodeId = n.id;
}
}
function resetSim(quiet = false) {
stopRun();
graph = migrateGraph(graph);
graph.semInit = Math.max(0, Number(els.semInit.value || graph.semInit || 0));
if (!graph.semDefaults) graph.semDefaults = {};
if (!Object.prototype.hasOwnProperty.call(graph.semDefaults, 'S')) graph.semDefaults.S = graph.semInit;
const oldLog = quiet ? sim.log.slice() : [];
sim = emptySim();
sim.log = oldLog;
ensureObjects();
const roster = getRoster();
const starts = graph.nodes.filter(n => n.type === 'start').sort((a,b) => a.y - b.y || a.x - b.x);
const spawned = new Set();
let autoThread = 0;
const uniqueThreadName = raw => {
const base = sanitizeName(raw, `T${autoThread++}`);
if (!spawned.has(base)) return base;
let i = 2;
while (spawned.has(`${base}_${i}`)) i += 1;
return `${base}_${i}`;
};
const spawn = (rawName, nodeId) => {
const id = uniqueThreadName(rawName);
sim.tokens.push({
id,
nodeId,
startNodeId: nodeId,
status: 'ready',
waiting: null,
phase: null,
local: null,
parentId: null,
spawnAlias: null
});
spawned.add(id);
};
starts.forEach((start, i) => {
const configured = start.ap || start.threadName || start.thread || `T${i}`;
if (configured === '*') {
for (const ap of roster) spawn(ap, start.id);
} else {
spawn(configured, start.id);
}
});
if (!sim.tokens.some(t => t.id === selectedTokenId)) selectedTokenId = sim.tokens[0]?.id || null;
rr = 0;
detectStall(false, { silent: true });
if (!quiet) {
const lens = lensInfo();
addLog(`Reset: ${sim.tokens.length} ${htmlEscape(lens.tokens)} token${sim.tokens.length === 1 ? '' : 's'} on ${graph.apCount} ${htmlEscape(lens.slots)} slot${graph.apCount === 1 ? '' : 's'}, counter=0.`, 'good');
if (!starts.length) addLog('No Start nodes exist, so no thread tokens were spawned.', 'warn');
}
renderAll();
}
function moveTokenToNext(t, fromId = t.nodeId) {
const to = nextId(fromId);
if (!to) {
t.status = 'done';
t.nodeId = fromId;
t.phase = null;
addLog(`${htmlEscape(t.id)} has no outgoing edge after <strong>${htmlEscape(nodeLabel(byId(fromId)))}</strong>; marked done.`, 'warn');
return false;
}
t.nodeId = to;
t.phase = null;
return true;
}
function blockToken(t, waiting) {
t.status = 'blocked';
t.waiting = waiting;
t.phase = null;
}
function unblockPastWaiter(waiterId, fromNodeId) {
const w = tokenById(waiterId);
if (!w) return;
w.status = 'ready';
w.waiting = null;
w.phase = null;
const to = nextId(fromNodeId);
if (to) w.nodeId = to;
}
function wakeJoiners() {
for (const t of sim.tokens) {
if (t.status !== 'blocked' || t.waiting?.kind !== 'join') continue;
const pending = (t.waiting.childIds || []).filter(cid => !isTerminalToken(tokenById(cid)));
if (pending.length) continue;
const fromNodeId = t.waiting.nodeId;
const joined = t.waiting.childIds || [];
t.status = 'ready';
t.waiting = null;
t.phase = null;
const to = nextId(fromNodeId);
if (to) t.nodeId = to;
else moveTokenToNext(t, fromNodeId);
addLog(`${htmlEscape(t.id)} join completes; child thread${joined.length === 1 ? '' : 's'} ${htmlEscape(childLabel(joined))} terminated.`, 'good');
}
}
function stepWork(t, n) {
const scenarioKey = n.workKind || 'plain';
const steps = workSteps(n);
if (!t.phase || t.phase.nodeId !== n.id || t.phase.kind !== 'work') {
t.phase = { kind: 'work', nodeId: n.id, scenario: scenarioKey, steps, done: 0, read: null };
}
const p = t.phase;
p.done += 1;
const label = htmlEscape(nodeLabel(n));
const progress = `${p.done}/${p.steps}`;
const value = Number(n.value || 0);
if (scenarioKey === 'plain') {
addLog(`${htmlEscape(t.id)} works at <strong>${label}</strong> (${progress}).`);
if (p.done >= p.steps) moveTokenToNext(t, n.id);
return;
}
if (scenarioKey === 'inc') {
if (p.done === 1) {
p.read = sim.counter;
t.local = sim.counter;
addLog(`${htmlEscape(t.id)} begins <strong>${label}</strong>: reads counter=<strong>${sim.counter}</strong> (${progress}).`, 'warn');
} else if (p.done < p.steps) {
addLog(`${htmlEscape(t.id)} computes from local=${htmlEscape(t.local)} at <strong>${label}</strong> (${progress}).`);
} else {
const before = sim.counter;
sim.counter = p.read + 1;
addLog(`${htmlEscape(t.id)} finishes <strong>${label}</strong>: writes ${p.read}+1 → counter=<strong>${sim.counter}</strong>${before !== p.read ? ' <em>(overwrote another update)</em>' : ''}.`, before !== p.read ? 'bad' : 'good');
t.local = null;
moveTokenToNext(t, n.id);
}
return;
}
if (scenarioKey === 'atomicInc') {
addLog(`${htmlEscape(t.id)} prepares atomic increment at <strong>${label}</strong> (${progress}).`);
if (p.done >= p.steps) {
const before = sim.counter;
sim.counter = before + 1;
addLog(`${htmlEscape(t.id)} performs one indivisible counter++: ${before} → <strong>${sim.counter}</strong>.`, 'good');
moveTokenToNext(t, n.id);
}
return;
}
if (scenarioKey === 'readCounter') {
addLog(`${htmlEscape(t.id)} reads at <strong>${label}</strong> (${progress}).`);
if (p.done >= p.steps) {
t.local = sim.counter;
addLog(`${htmlEscape(t.id)} stores local=<strong>${sim.counter}</strong>.`, 'good');
moveTokenToNext(t, n.id);
}
return;
}
if (scenarioKey === 'writeLocalPlusOne') {
addLog(`${htmlEscape(t.id)} prepares write at <strong>${label}</strong> (${progress}).`);
if (p.done >= p.steps) {
if (typeof t.local !== 'number') {
t.status = 'error';
addLog(`${htmlEscape(t.id)} cannot write local+1 because it has no numeric local value.`, 'bad');
return;
}
const before = sim.counter;
sim.counter = t.local + 1;
addLog(`${htmlEscape(t.id)} writes local+1 (${t.local}+1) → counter=<strong>${sim.counter}</strong>${before !== t.local ? ' <em>(possible lost update)</em>' : ''}.`, before !== t.local ? 'bad' : 'good');
t.local = null;
moveTokenToNext(t, n.id);
}
return;
}
if (scenarioKey === 'setCounter') {
addLog(`${htmlEscape(t.id)} prepares set counter at <strong>${label}</strong> (${progress}).`);
if (p.done >= p.steps) {
sim.counter = value;
addLog(`${htmlEscape(t.id)} sets counter=<strong>${value}</strong>.`, 'good');
moveTokenToNext(t, n.id);
}
return;
}
addLog(`${htmlEscape(t.id)} does unknown work scenario; treating as plain work.`, 'warn');
if (p.done >= p.steps) moveTokenToNext(t, n.id);
}
function releaseMutexFor(obj, ownerId) {
const m = sim.mutexes[obj] || (sim.mutexes[obj] = { owner: null, queue: [] });
if (m.owner !== ownerId) return { ok: false, owner: m.owner || null, woken: null, queue: m.queue.slice() };
if (m.queue.length) {
const wId = m.queue.shift();
const w = tokenById(wId);
const waitInfo = w?.waiting ? { ...w.waiting } : null;
const waitNodeId = w?.waiting?.nodeId;
m.owner = wId;
if (waitNodeId) unblockPastWaiter(wId, waitNodeId);
return { ok: true, owner: m.owner, woken: wId, waitInfo, queue: m.queue.slice() };
}
m.owner = null;
return { ok: true, owner: null, woken: null, waitInfo: null, queue: m.queue.slice() };
}
function wakeCondWaiter(waiterId, condObj, byIdForLog) {
const w = tokenById(waiterId);
if (!w) return false;
const waitInfo = w.waiting || {};
const mutexObj = waitInfo.mutex || 'M';
const waitNodeId = waitInfo.nodeId;
const m = sim.mutexes[mutexObj] || (sim.mutexes[mutexObj] = { owner: null, queue: [] });
if (!m.owner) {
m.owner = waiterId;
w.status = 'ready';
w.waiting = null;
w.phase = null;
const to = nextId(waitNodeId);
if (to) w.nodeId = to;
addLog(`${htmlEscape(byIdForLog)} wakes ${htmlEscape(waiterId)} on cond <strong>${htmlEscape(condObj)}</strong>; ${htmlEscape(waiterId)} immediately re-locks mutex <strong>${htmlEscape(mutexObj)}</strong> and continues.`, 'good');
} else {
if (!m.queue.includes(waiterId)) m.queue.push(waiterId);
blockToken(w, { kind: 'cond-relock', obj: condObj, mutex: mutexObj, nodeId: waitNodeId });
addLog(`${htmlEscape(byIdForLog)} wakes ${htmlEscape(waiterId)} on cond <strong>${htmlEscape(condObj)}</strong>; it must re-lock mutex <strong>${htmlEscape(mutexObj)}</strong>, currently owned by ${htmlEscape(m.owner)}.`, 'warn');
}
return true;
}
function stepToken(id, options = {}) {
ensureObjects();
const t = tokenById(id);
if (!t) { addLog(`No thread named ${htmlEscape(id)} is currently spawned.`, 'warn'); return false; }
if (t.status === 'done') { addLog(`${htmlEscape(id)} is already done.`, 'warn'); return false; }
if (t.status === 'error') { addLog(`${htmlEscape(id)} is stopped on an error. Reset to continue.`, 'bad'); return false; }
if (t.status === 'blocked') { addLog(`${htmlEscape(id)} is blocked on ${htmlEscape(describeWaiting(t.waiting))}.`, 'warn'); return false; }
const n = byId(t.nodeId);
if (!n) { t.status = 'error'; addLog(`${htmlEscape(id)} points at a missing node.`, 'bad'); renderAll(); return false; }
if (options.countTick !== false) {
sim.tick += 1;
sim.lastTickRan = [id];
}
sim.micro += 1;
switch (n.type) {