lamellar 0.8.1

Lamellar is an asynchronous tasking runtime for HPC systems developed in RUST.
Documentation
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
use crate::{
    active_messaging::batching::{
        simple_batcher::io_task_stats, BATCHER_AM_PE_RECV_CNTS, BATCHER_AM_PE_SEND_CNTS,
    },
    env_var::config,
    lamellae::{AllocationType, CommAllocRdma, CommProgress, CommSlice, Lamellae},
    lamellar_arch::LamellarArchRT,
    lamellar_request::LamellarRequest,
    memregion::MemoryRegion,
    scheduler::Scheduler,
    utils::print_stats,
    warnings::RuntimeWarning,
};

use futures_util::Future;
use pin_project::{pin_project, pinned_drop};
use std::pin::Pin;
use std::sync::{
    atomic::{AtomicU8, AtomicUsize, Ordering},
    Arc,
};
use std::task::{Context, Poll, Waker};
use std::time::Instant;
use tracing::{debug, trace};

pub(crate) struct Barrier {
    my_pe: usize, // global pe id
    num_pes: usize,
    n: usize, // dissemination factor
    num_rounds: usize,
    pub(crate) arch: Arc<LamellarArchRT>,
    pub(crate) scheduler: Arc<Scheduler>,
    lamellae: Arc<Lamellae>,
    barrier_cnt: AtomicUsize,
    cur_barrier_id: Arc<AtomicUsize>,
    barrier_mem_region: Option<MemoryRegion<usize>>, //keep mem region alive
    barrier_buf: Arc<Vec<CommSlice<usize>>>,
    // send_buf: Option<MemoryRegion<usize>>,
    panic: Arc<AtomicU8>,
}

// impl Drop for Barrier {
//     fn drop(&mut self) {
//         trace!(target: "lamellae_debug",  "Dropping Barrier for my_pe {:?} lamellae cnt: {:?} ", self.my_pe, Arc::strong_count(&self.lamellae));
//     }
// }

impl Barrier {
    pub(crate) fn new(
        my_pe: usize,
        global_pes: usize,
        lamellae: Arc<Lamellae>,
        arch: Arc<LamellarArchRT>,
        scheduler: Arc<Scheduler>,
        panic: Arc<AtomicU8>,
    ) -> Barrier {
        let num_pes = arch.num_pes();
        // let mut n = std::env::var("LAMELLAR_BARRIER_DISSEMNATION_FACTOR")
        let mut n = config().barrier_dissemination_factor;
        let num_rounds = if n > 1 && num_pes > 2 {
            ((num_pes as f64).log2() / (n as f64).log2()).ceil() as usize
        } else {
            n = 1;
            (num_pes as f64).log2() as usize
        };
        let (mem_region, buffs) = if let Ok(_my_index) = arch.team_pe(my_pe) {
            if num_pes > 1 {
                let alloc = if global_pes == arch.num_pes() {
                    AllocationType::Global
                } else {
                    let mut pes = arch.team_iter().collect::<Vec<usize>>();
                    pes.sort();
                    AllocationType::Sub(pes)
                };
                trace!(target: "lamellae_debug", "creating barrier with alloc {:?} for my_pe {:?} num_pes {:?} num_rounds {:?} n {:?} lamellae cnt: {:?}", alloc, my_pe, num_pes, num_rounds, n, Arc::strong_count(&lamellae));
                let mem_region =
                    MemoryRegion::new(num_rounds * n, &scheduler, None, &lamellae, alloc.clone());
                let mem_region_comm_slice = unsafe {
                    mem_region.as_comm_slice().expect(
                        "MemoryRegion should be registered and able to be converted to CommSlice",
                    )
                };
                let mut buffs = vec![];
                for r in 0..n {
                    trace!(
                        target: "lamellae_debug",
                        "[r: {r}] creating barrier buff {:?}, num_rounds: {num_rounds} lamellae cnt: {:?}",
                        alloc,
                        Arc::strong_count(&lamellae)
                    );
                    buffs.push(
                        mem_region_comm_slice.sub_slice(r * num_rounds..(r + 1) * num_rounds),
                    );
                }

                // let send_buf = MemoryRegion::new(1, &scheduler, vec![], &lamellae, alloc);

                unsafe {
                    for buff in &mut buffs {
                        for elem in buff.as_mut_slice() {
                            *elem = 0;
                        }
                    }
                }
                (Some(mem_region), buffs)
            } else {
                (None, vec![])
            }
        } else {
            (None, vec![])
        };

        let bar = Barrier {
            my_pe,
            num_pes,
            n,
            num_rounds,
            arch,
            scheduler,
            lamellae,
            barrier_cnt: AtomicUsize::new(1),
            barrier_mem_region: mem_region,
            cur_barrier_id: Arc::new(AtomicUsize::new(1)),
            barrier_buf: Arc::new(buffs),
            panic,
        };
        // bar.print_bar();
        trace!(target: "lamellae_debug", "Created Barrier for my_pe: {:?} num_pes: {:?} n: {:?} num_rounds: {:?} lamellae cnt: {:?}", my_pe, num_pes, n, num_rounds, Arc::strong_count(&bar.lamellae));
        bar
    }

    fn print_bar(&self) {
        if let Some(_) = &self.barrier_mem_region {
            let buffs = self
                .barrier_buf
                .iter()
                .map(|b| b.as_slice())
                .collect::<Vec<_>>();
            println!(
                " [LAMELLAR BARRIER][{:?}][{:?}][{:?}] {:?}  {:?}",
                std::thread::current().id(),
                self.my_pe,
                self.barrier_buf[0],
                buffs,
                self.barrier_cnt.load(Ordering::SeqCst)
            );
        }
    }

    fn barrier_timeout(
        &self,
        s: &mut Instant,
        my_index: usize,
        round: usize,
        i: usize,
        team_recv_pe: isize,
        recv_pe: usize,
        barrier_id: usize,
    ) {
        RuntimeWarning::BarrierTimeout(s.elapsed().as_secs_f64()).print();

        if s.elapsed().as_secs_f64() > config().deadlock_warning_timeout {
            self.lamellae.wait_all_print();

            println!(
                "[{:?}][{:?}, {:?}] round: {:?} i: {:?} teamsend_pe: {:?} team_recv_pe: {:?} recv_pe: {:?} id: {:?} buf {:?} AM send/recv counts: {:?} {:?} {:?}",
                std::thread::current().id(),
                self.my_pe,
                my_index,
                round,
                i,
                (my_index + i * (self.n + 1).pow(round as u32))
                    % self.num_pes,
                team_recv_pe,
                recv_pe,
                barrier_id,
                    self.barrier_buf[i - 1]
                        .as_slice(),
                    print_stats!(&*BATCHER_AM_PE_SEND_CNTS),
                    print_stats!(&*BATCHER_AM_PE_RECV_CNTS),
                        io_task_stats(),
            );
            self.print_bar();
            *s = Instant::now();
        }
    }

    fn barrier_internal<F: Fn()>(&self, wait_func: F) {
        // println!("in barrier");
        // self.print_bar();
        trace!(
            "[{:?}] entering barrier cnt: {:?} cur_barrier_id: {:?}",
            std::thread::current().id(),
            self.barrier_cnt.load(Ordering::SeqCst),
            self.cur_barrier_id.load(Ordering::SeqCst)
        );
        let mut s = Instant::now();
        if self.panic.load(Ordering::SeqCst) == 0 {
            if let Some(_) = &self.barrier_mem_region {
                if let Ok(my_index) = self.arch.team_pe(self.my_pe) {
                    let barrier_id = self.barrier_cnt.fetch_add(1, Ordering::SeqCst);

                    trace!(
                        "[{:?}] barrier_id = {:?}",
                        std::thread::current().id(),
                        barrier_id
                    );
                    while barrier_id > self.cur_barrier_id.load(Ordering::SeqCst) {
                        wait_func();
                        if s.elapsed().as_secs_f64() > config().deadlock_warning_timeout {
                            break;
                        }
                        self.lamellae.comm().flush_all();
                    }

                    for round in 0..self.num_rounds {
                        trace!(
                            "[{:?}][ {:?} {:?}] round: {:?} barrier_id: {:?}",
                            std::thread::current().id(),
                            self.my_pe,
                            my_index,
                            round,
                            barrier_id
                        );
                        // let mut reqs = vec![];
                        for i in 1..=self.n {
                            let team_send_pe =
                                (my_index + i * (self.n + 1).pow(round as u32)) % self.num_pes;
                            trace!(
                                    "[{:?}][ {:?} {:?}] round: {:?}  i: {:?} sending to [ ({:?}) ] id: {:?} buf {:?}",
                                    std::thread::current().id(),
                                    self.my_pe,
                                    my_index,
                                    round,
                                    i,
                                    team_send_pe,
                                    barrier_id,
                                        self.barrier_buf[i - 1]
                                            .as_slice()
                                    );
                            if team_send_pe != my_index {
                                let send_pe = self.arch.single_iter(team_send_pe).next().unwrap();

                                // println!("barrier put_slice 1");
                                // reqs.push(
                                self.barrier_buf[i - 1].put_unmanaged(barrier_id, send_pe, round);
                                // );
                                // let _ = self.barrier_buf[i - 1]
                                //     .put_comm_slice(
                                //         send_pe,
                                //         round,
                                //         CommSlice::from_slice(barrier_slice),
                                //     )
                                //     .spawn(); //no need to pass in counters as we wont leave until the barrier is complete anyway
                                //safe as we are the only ones writing to our index
                            }
                        }
                        // join_all(reqs).await;
                        // for req in reqs.into_iter() {
                        //     req.block();
                        // }
                        self.barrier_buf[0].wait();
                        for i in 1..=self.n {
                            let team_recv_pe = ((my_index as isize
                                - (i as isize * (self.n as isize + 1).pow(round as u32) as isize))
                                as isize)
                                .rem_euclid(self.num_pes as isize)
                                as isize;
                            let recv_pe =
                                self.arch.single_iter(team_recv_pe as usize).next().unwrap();
                            if team_recv_pe as usize != my_index {
                                trace!(
                                    "[{:?}][{:?} ] recv from [{:?} ({:?}) ] id: {:?} buf {:?}",
                                    std::thread::current().id(),
                                    self.my_pe,
                                    recv_pe,
                                    team_recv_pe,
                                    barrier_id,
                                    self.barrier_buf[i - 1].as_slice()
                                );

                                //safe as  each pe is only capable of writing to its own index
                                while self.barrier_buf[i - 1].as_slice()[round] < barrier_id {
                                    self.barrier_timeout(
                                        &mut s,
                                        my_index,
                                        round,
                                        i,
                                        team_recv_pe,
                                        recv_pe,
                                        barrier_id,
                                    );
                                    self.lamellae.comm().flush_all();
                                    wait_func();
                                }
                            }
                        }
                    }
                    self.cur_barrier_id.store(barrier_id + 1, Ordering::SeqCst);
                    // println!("leaving barrier {:?}", barrier_id);
                }
            }
        }

        // self.print_bar();
        // self.lamellae.comm().flush();
    }

    pub(crate) fn barrier(&self) {
        if std::thread::current().id() == *crate::MAIN_THREAD {
            self.barrier_internal(|| {
                // std::thread::yield_now();
                self.scheduler.exec_task();
            });
        } else {
            RuntimeWarning::BlockingCall("barrier", "async_barrier().await").print();
            self.tasking_barrier()
        }
    }

    // typically we want to block on the barrier and  spin on the barrier flags so that we can quick resume
    // but for the case of Darcs, or any case where the barrier is being called in a worker thread
    // we actually want to be able to process other tasks while the barrier is active
    pub(crate) fn tasking_barrier(&self) {
        // println!("calling tasking barrier");
        self.barrier_internal(|| {
            self.scheduler.exec_task();
        });
    }

    pub(crate) fn barrier_handle(&self) -> BarrierHandle {
        let mut handle = BarrierHandle {
            barrier_buf: self.barrier_buf.clone(),
            arch: self.arch.clone(),
            scheduler: self.scheduler.clone(),
            lamellae: self.lamellae.clone(),
            my_index: 0,
            num_pes: self.num_pes,
            barrier_id: 0,
            cur_barrier_id: self.cur_barrier_id.clone(),
            num_rounds: self.num_rounds,
            n: self.n,
            state: State::RoundInit(self.num_rounds),
            launched: false,
        };
        trace!("in barrier handle");
        // self.print_bar();
        if self.panic.load(Ordering::SeqCst) == 0 {
            if let Some(_) = &self.barrier_mem_region {
                if let Ok(my_index) = self.arch.team_pe(self.my_pe) {
                    let barrier_id = self.barrier_cnt.fetch_add(1, Ordering::SeqCst);
                    trace!("barrier id: {:?}", barrier_id);
                    debug!(target: "barrier", my_pe = self.my_pe, thread = ?std::thread::current().id(), barrier_id, cur_barrier_id = self.cur_barrier_id.load(Ordering::SeqCst), "barrier_handle created, drew barrier_id");
                    handle.barrier_id = barrier_id;
                    handle.my_index = my_index;

                    if barrier_id > self.cur_barrier_id.load(Ordering::SeqCst) {
                        debug!(target: "barrier", my_pe = self.my_pe, thread = ?std::thread::current().id(), barrier_id, cur_barrier_id = self.cur_barrier_id.load(Ordering::SeqCst), "barrier_id ahead of cur_barrier_id, entering Waiting state");
                        handle.state = State::Waiting;
                        return handle;
                    }
                    // else if barrier_id < self.cur_barrier_id.load(Ordering::SeqCst) {
                    //     println!("should this happen>?");
                    // }

                    handle.state = State::RoundInit(0);
                    let mut round = 0;
                    while round < self.num_rounds {
                        handle.do_send_round(round);
                        if let Some(recv_pe) = handle.do_recv_round(round, 1) {
                            debug!(target: "barrier", my_pe = self.my_pe, thread = ?std::thread::current().id(), barrier_id, round, recv_pe, "round in progress, awaiting recv_pe (sync path)");
                            handle.state = State::RoundInProgress(round, recv_pe);
                            return handle;
                        }
                        round += 1;
                    }
                    debug!(target: "barrier", my_pe = self.my_pe, thread = ?std::thread::current().id(), barrier_id, "barrier completed synchronously in barrier_handle(), advancing cur_barrier_id");
                    self.cur_barrier_id.store(barrier_id + 1, Ordering::SeqCst);
                    handle.state = State::RoundInit(self.num_rounds);
                }
            }
        }
        handle
    }

    pub(crate) async fn async_barrier(&self) {
        self.barrier_handle().await;
    }
}

// impl Drop for Barrier {
//     fn drop(&mut self) {
//         println!("dropping barrier");
//         println!("lamellae cnt: {:?}", Arc::strong_count(&self.lamellae));
//         println!("scheduler cnt: {:?}", Arc::strong_count(&self.scheduler));
//         println!("dropped barrier");
//     }
// }

/// A handle to a Lamellar barrier that can be used to wait on the barrier
#[pin_project(PinnedDrop)]
pub struct BarrierHandle {
    barrier_buf: Arc<Vec<CommSlice<usize>>>,
    arch: Arc<LamellarArchRT>,
    scheduler: Arc<Scheduler>,
    lamellae: Arc<Lamellae>,
    my_index: usize,
    num_pes: usize,
    pub(crate) barrier_id: usize,
    cur_barrier_id: Arc<AtomicUsize>,
    num_rounds: usize,
    n: usize,
    state: State,
    launched: bool,
}

#[pinned_drop]
impl PinnedDrop for BarrierHandle {
    fn drop(self: Pin<&mut Self>) {
        trace!(target: "lamellae_debug",  "Dropping BarrierHandle  lamellae cnt: {:?} ", Arc::strong_count(&self.lamellae));
        if !self.launched {
            RuntimeWarning::DroppedHandle("a BarrierHandle").print();
        }
    }
}

enum State {
    Waiting,
    RoundInit(usize),              //the round we are in
    RoundInProgress(usize, usize), //the round we are in, pe we are waiting to hear from
}

impl BarrierHandle {
    fn do_send_round(&self, round: usize) {
        trace!("do send round {:?}", round);
        // let barrier_slice = &[self.barrier_id];
        // let mut reqs = vec![];
        for i in 1..=self.n {
            let team_send_pe = (self.my_index + i * (self.n + 1).pow(round as u32)) % self.num_pes;
            if team_send_pe != self.my_index {
                let send_pe = self.arch.single_iter(team_send_pe).next().unwrap();
                trace!("sending to pe {:?} for round {:?}", send_pe, round);
                self.barrier_buf[i - 1].put_unmanaged(self.barrier_id, send_pe, round);
            }
        }
        // for req in reqs.into_iter() {
        //     req.block();
        // }
        trace!("waiting on sends to complete for round {:?}", round);
        self.barrier_buf[0].wait();
    }

    fn do_recv_round(&self, round: usize, recv_pe_index: usize) -> Option<usize> {
        // trace!("do recv round {:?}", round);
        for i in recv_pe_index..=self.n {
            let team_recv_pe = ((self.my_index as isize
                - (i as isize * (self.n as isize + 1).pow(round as u32) as isize))
                as isize)
                .rem_euclid(self.num_pes as isize) as isize;
            // let recv_pe = self.arch.single_iter(team_recv_pe as usize).next().unwrap();
            if team_recv_pe as usize != self.my_index {
                //safe as  each pe is only capable of writing to its own index
                if self.barrier_buf[i - 1].as_slice()[round] < self.barrier_id {
                    self.lamellae.comm().thread_flush();
                    // trace!("waiting for recv pe: {:?} round: {:?} i: {:?}",  team_recv_pe, round, i);
                    return Some(i);
                }
            }
        }
        // trace!("dont need to wait for any recv pe");
        None
    }
}

impl Future for BarrierHandle {
    type Output = ();
    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        // let mut this = self.project();
        self.launched = true;
        match self.state {
            State::Waiting => {
                let cur = self.cur_barrier_id.load(Ordering::SeqCst);
                if self.barrier_id > cur {
                    debug!(target: "barrier", thread = ?std::thread::current().id(), barrier_id = self.barrier_id, cur_barrier_id = cur, "poll: still Waiting, barrier_id ahead");
                    cx.waker().wake_by_ref();
                    return Poll::Pending;
                }
                // else if self.barrier_id < self.cur_barrier_id.load(Ordering::SeqCst) {
                //     println!("barrier id is less than cur barrier id");
                // }
                debug!(target: "barrier", thread = ?std::thread::current().id(), barrier_id = self.barrier_id, cur_barrier_id = cur, "poll: Waiting -> RoundInit(0)");
                *self.project().state = State::RoundInit(0);
                cx.waker().wake_by_ref();
                Poll::Pending
            }
            State::RoundInit(round) => {
                let mut round = round;
                while round < self.num_rounds {
                    self.do_send_round(round);
                    if let Some(recv_pe) = self.do_recv_round(round, 1) {
                        // println!("waiting for pe {:?}", recv_pe);
                        debug!(target: "barrier", thread = ?std::thread::current().id(), barrier_id = self.barrier_id, round, recv_pe, "poll: RoundInit -> RoundInProgress, waiting on recv_pe");
                        *self.project().state = State::RoundInProgress(round, recv_pe);
                        cx.waker().wake_by_ref();
                        return Poll::Pending;
                    }
                    round += 1;
                }
                debug!(target: "barrier", thread = ?std::thread::current().id(), barrier_id = self.barrier_id, "poll: RoundInit complete, all rounds done, advancing cur_barrier_id, Ready");
                self.cur_barrier_id
                    .store(self.barrier_id + 1, Ordering::SeqCst);
                *self.project().state = State::RoundInit(round);

                Poll::Ready(())
            }
            State::RoundInProgress(round, recv_pe) => {
                let mut round = round;
                if let Some(recv_pe) = self.do_recv_round(round, recv_pe) {
                    // println!("waiting for pe {:?}", recv_pe);
                    *self.project().state = State::RoundInProgress(round, recv_pe);
                    cx.waker().wake_by_ref();
                    return Poll::Pending;
                }
                round += 1;
                while round < self.num_rounds {
                    self.do_send_round(round);
                    if let Some(recv_pe) = self.do_recv_round(round, 1) {
                        // println!("waiting for pe {:?}", recv_pe);
                        debug!(target: "barrier", thread = ?std::thread::current().id(), barrier_id = self.barrier_id, round, recv_pe, "poll: RoundInProgress continuing, waiting on next recv_pe");
                        *self.project().state = State::RoundInProgress(round, recv_pe);
                        cx.waker().wake_by_ref();
                        return Poll::Pending;
                    }
                    round += 1;
                }
                debug!(target: "barrier", thread = ?std::thread::current().id(), barrier_id = self.barrier_id, "poll: RoundInProgress complete, all rounds done, advancing cur_barrier_id, Ready");
                self.cur_barrier_id
                    .store(self.barrier_id + 1, Ordering::SeqCst);
                *self.project().state = State::RoundInit(round);

                Poll::Ready(())
            }
        }
    }
}

impl LamellarRequest for BarrierHandle {
    fn launch(&mut self) {
        self.launched = true;
    }
    fn blocking_wait(mut self) -> Self::Output {
        self.launched = true;
        match self.state {
            State::Waiting => {
                while self.barrier_id > self.cur_barrier_id.load(Ordering::SeqCst) {
                    std::thread::yield_now();
                }
                if self.barrier_id < self.cur_barrier_id.load(Ordering::SeqCst) {
                    println!("barrier id is less than cur barrier id");
                }
                let mut round = 0;
                while round < self.num_rounds {
                    self.do_send_round(round);
                    let mut recv_pe_index = 1;
                    while let Some(recv_pe) = self.do_recv_round(round, recv_pe_index) {
                        recv_pe_index = recv_pe;
                        std::thread::yield_now();
                    }
                    round += 1;
                }
                self.cur_barrier_id
                    .store(self.barrier_id + 1, Ordering::SeqCst);
            }
            State::RoundInit(round) => {
                let mut round = round;
                while round < self.num_rounds {
                    self.do_send_round(round);
                    let mut recv_pe_index = 1;
                    while let Some(recv_pe) = self.do_recv_round(round, recv_pe_index) {
                        recv_pe_index = recv_pe;
                        std::thread::yield_now();
                    }
                    round += 1;
                }
                self.cur_barrier_id
                    .store(self.barrier_id + 1, Ordering::SeqCst);
            }
            State::RoundInProgress(round, recv_pe) => {
                let mut round = round;
                let mut recv_pe_index = recv_pe;
                while let Some(_recv_pe) = self.do_recv_round(round, recv_pe_index) {
                    recv_pe_index = recv_pe;
                    std::thread::yield_now();
                }
                round += 1;
                while round < self.num_rounds {
                    recv_pe_index = 1;
                    while let Some(recv_pe) = self.do_recv_round(round, recv_pe_index) {
                        recv_pe_index = recv_pe;
                        std::thread::yield_now();
                    }
                    round += 1;
                }
                self.cur_barrier_id
                    .store(self.barrier_id + 1, Ordering::SeqCst);
            }
        }
    }

    fn ready_or_set_waker(&mut self, _waker: &Waker) -> bool {
        self.launched = true;
        match self.state {
            State::Waiting => false,
            State::RoundInit(round) => {
                if round < self.num_rounds {
                    false
                } else {
                    true
                }
            }
            State::RoundInProgress(round, _) => {
                if round < self.num_rounds {
                    false
                } else {
                    true
                }
            }
        }
    }

    fn val(&self) -> Self::Output {
        match self.state {
            State::Waiting => {
                while self.barrier_id > self.cur_barrier_id.load(Ordering::SeqCst) {
                    std::thread::yield_now();
                }
                // if self.barrier_id < self.cur_barrier_id.load(Ordering::SeqCst) {
                //     println!("barrier id is less than cur barrier id");
                // }
                let mut round = 0;
                while round < self.num_rounds {
                    self.do_send_round(round);
                    let mut recv_pe_index = 1;
                    while let Some(recv_pe) = self.do_recv_round(round, recv_pe_index) {
                        recv_pe_index = recv_pe;
                        std::thread::yield_now();
                    }
                    round += 1;
                }
                self.cur_barrier_id
                    .store(self.barrier_id + 1, Ordering::SeqCst);
            }
            State::RoundInit(round) => {
                let mut round = round;
                while round < self.num_rounds {
                    self.do_send_round(round);
                    let mut recv_pe_index = 1;
                    while let Some(recv_pe) = self.do_recv_round(round, recv_pe_index) {
                        recv_pe_index = recv_pe;
                        std::thread::yield_now();
                    }
                    round += 1;
                }
                self.cur_barrier_id
                    .store(self.barrier_id + 1, Ordering::SeqCst);
            }
            State::RoundInProgress(round, recv_pe) => {
                let mut round = round;
                let mut recv_pe_index = recv_pe;
                while let Some(recv_pe) = self.do_recv_round(round, recv_pe_index) {
                    recv_pe_index = recv_pe;
                    std::thread::yield_now();
                }
                round += 1;
                while round < self.num_rounds {
                    recv_pe_index = 1;
                    while let Some(recv_pe) = self.do_recv_round(round, recv_pe_index) {
                        recv_pe_index = recv_pe;
                        std::thread::yield_now();
                    }
                    round += 1;
                }
                self.cur_barrier_id
                    .store(self.barrier_id + 1, Ordering::SeqCst);
            }
        }
    }
}