LCOV - code coverage report
Current view: top level - libs/desim/src - executor.rs (source / functions) Coverage Total Hit
Test: 8b13a09a5c233d98abd4a0d3e59157e7db16d6fd.info Lines: 96.8 % 281 272
Test Date: 2024-11-21 10:53:51 Functions: 89.7 % 145 130

            Line data    Source code
       1              : use std::{
       2              :     panic::AssertUnwindSafe,
       3              :     sync::{
       4              :         atomic::{AtomicBool, AtomicU32, AtomicU8, Ordering},
       5              :         mpsc, Arc, OnceLock,
       6              :     },
       7              :     thread::JoinHandle,
       8              : };
       9              : 
      10              : use tracing::{debug, error, trace};
      11              : 
      12              : use crate::time::Timing;
      13              : 
      14              : /// Stores status of the running threads. Threads are registered in the runtime upon creation
      15              : /// and deregistered upon termination.
      16              : pub struct Runtime {
      17              :     // stores handles to all threads that are currently running
      18              :     threads: Vec<ThreadHandle>,
      19              :     // stores current time and pending wakeups
      20              :     clock: Arc<Timing>,
      21              :     // thread counter
      22              :     thread_counter: AtomicU32,
      23              :     // Thread step counter -- how many times all threads has been actually
      24              :     // stepped (note that all world/time/executor/thread have slightly different
      25              :     // meaning of steps). For observability.
      26              :     pub step_counter: u64,
      27              : }
      28              : 
      29              : impl Runtime {
      30              :     /// Init new runtime, no running threads.
      31          528 :     pub fn new(clock: Arc<Timing>) -> Self {
      32          528 :         Self {
      33          528 :             threads: Vec::new(),
      34          528 :             clock,
      35          528 :             thread_counter: AtomicU32::new(0),
      36          528 :             step_counter: 0,
      37          528 :         }
      38          528 :     }
      39              : 
      40              :     /// Spawn a new thread and register it in the runtime.
      41        19270 :     pub fn spawn<F>(&mut self, f: F) -> ExternalHandle
      42        19270 :     where
      43        19270 :         F: FnOnce() + Send + 'static,
      44        19270 :     {
      45        19270 :         let (tx, rx) = mpsc::channel();
      46        19270 : 
      47        19270 :         let clock = self.clock.clone();
      48        19270 :         let tid = self.thread_counter.fetch_add(1, Ordering::SeqCst);
      49        19270 :         debug!("spawning thread-{}", tid);
      50              : 
      51        19270 :         let join = std::thread::spawn(move || {
      52        19270 :             let _guard = tracing::info_span!("", tid).entered();
      53        19270 : 
      54        19270 :             let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
      55        19270 :                 with_thread_context(|ctx| {
      56        19270 :                     assert!(ctx.clock.set(clock).is_ok());
      57        19270 :                     ctx.id.store(tid, Ordering::SeqCst);
      58        19270 :                     tx.send(ctx.clone()).expect("failed to send thread context");
      59        19270 :                     // suspend thread to put it to `threads` in sleeping state
      60        19270 :                     ctx.yield_me(0);
      61        19270 :                 });
      62        19270 : 
      63        19270 :                 // start user-provided function
      64        19270 :                 f();
      65        19270 :             }));
      66        19270 :             debug!("thread finished");
      67              : 
      68        19212 :             if let Err(e) = res {
      69        19192 :                 with_thread_context(|ctx| {
      70        19192 :                     if !ctx.allow_panic.load(std::sync::atomic::Ordering::SeqCst) {
      71            0 :                         error!("thread panicked, terminating the process: {:?}", e);
      72            0 :                         std::process::exit(1);
      73        19192 :                     }
      74        19192 : 
      75        19192 :                     debug!("thread panicked: {:?}", e);
      76        19192 :                     let mut result = ctx.result.lock();
      77        19192 :                     if result.0 == -1 {
      78        18736 :                         *result = (256, format!("thread panicked: {:?}", e));
      79        18736 :                     }
      80        19192 :                 });
      81        19192 :             }
      82              : 
      83        19212 :             with_thread_context(|ctx| {
      84        19212 :                 ctx.finish_me();
      85        19212 :             });
      86        19270 :         });
      87        19270 : 
      88        19270 :         let ctx = rx.recv().expect("failed to receive thread context");
      89        19270 :         let handle = ThreadHandle::new(ctx.clone(), join);
      90        19270 : 
      91        19270 :         self.threads.push(handle);
      92        19270 : 
      93        19270 :         ExternalHandle { ctx }
      94        19270 :     }
      95              : 
      96              :     /// Returns true if there are any unfinished activity, such as running thread or pending events.
      97              :     /// Otherwise returns false, which means all threads are blocked forever.
      98       411786 :     pub fn step(&mut self) -> bool {
      99       411786 :         trace!("runtime step");
     100              : 
     101              :         // have we run any thread?
     102       411786 :         let mut ran = false;
     103       411786 : 
     104      2054554 :         self.threads.retain(|thread: &ThreadHandle| {
     105      2054554 :             let res = thread.ctx.wakeup.compare_exchange(
     106      2054554 :                 PENDING_WAKEUP,
     107      2054554 :                 NO_WAKEUP,
     108      2054554 :                 Ordering::SeqCst,
     109      2054554 :                 Ordering::SeqCst,
     110      2054554 :             );
     111      2054554 :             if res.is_err() {
     112              :                 // thread has no pending wakeups, leaving as is
     113      1771213 :                 return true;
     114       283341 :             }
     115       283341 :             ran = true;
     116       283341 : 
     117       283341 :             trace!("entering thread-{}", thread.ctx.tid());
     118       283341 :             let status = thread.step();
     119       283341 :             self.step_counter += 1;
     120       283341 :             trace!(
     121            0 :                 "out of thread-{} with status {:?}",
     122            0 :                 thread.ctx.tid(),
     123              :                 status
     124              :             );
     125              : 
     126       283341 :             if status == Status::Sleep {
     127       264129 :                 true
     128              :             } else {
     129        19212 :                 trace!("thread has finished");
     130              :                 // removing the thread from the list
     131        19212 :                 false
     132              :             }
     133      2054554 :         });
     134       411786 : 
     135       411786 :         if !ran {
     136       217300 :             trace!("no threads were run, stepping clock");
     137       217300 :             if let Some(ctx_to_wake) = self.clock.step() {
     138       216752 :                 trace!("waking up thread-{}", ctx_to_wake.tid());
     139       216752 :                 ctx_to_wake.inc_wake();
     140              :             } else {
     141          548 :                 return false;
     142              :             }
     143       194486 :         }
     144              : 
     145       411238 :         true
     146       411786 :     }
     147              : 
     148              :     /// Kill all threads. This is done by setting a flag in each thread context and waking it up.
     149         1008 :     pub fn crash_all_threads(&mut self) {
     150         2853 :         for thread in self.threads.iter() {
     151         2853 :             thread.ctx.crash_stop();
     152         2853 :         }
     153              : 
     154              :         // all threads should be finished after a few steps
     155         1512 :         while !self.threads.is_empty() {
     156          504 :             self.step();
     157          504 :         }
     158         1008 :     }
     159              : }
     160              : 
     161              : impl Drop for Runtime {
     162          503 :     fn drop(&mut self) {
     163          503 :         debug!("dropping the runtime");
     164          503 :         self.crash_all_threads();
     165          503 :     }
     166              : }
     167              : 
     168              : #[derive(Clone)]
     169              : pub struct ExternalHandle {
     170              :     ctx: Arc<ThreadContext>,
     171              : }
     172              : 
     173              : impl ExternalHandle {
     174              :     /// Returns true if thread has finished execution.
     175       425302 :     pub fn is_finished(&self) -> bool {
     176       425302 :         let status = self.ctx.mutex.lock();
     177       425302 :         *status == Status::Finished
     178       425302 :     }
     179              : 
     180              :     /// Returns exitcode and message, which is available after thread has finished execution.
     181          448 :     pub fn result(&self) -> (i32, String) {
     182          448 :         let result = self.ctx.result.lock();
     183          448 :         result.clone()
     184          448 :     }
     185              : 
     186              :     /// Returns thread id.
     187           14 :     pub fn id(&self) -> u32 {
     188           14 :         self.ctx.id.load(Ordering::SeqCst)
     189           14 :     }
     190              : 
     191              :     /// Sets a flag to crash thread on the next wakeup.
     192        16224 :     pub fn crash_stop(&self) {
     193        16224 :         self.ctx.crash_stop();
     194        16224 :     }
     195              : }
     196              : 
     197              : struct ThreadHandle {
     198              :     ctx: Arc<ThreadContext>,
     199              :     _join: JoinHandle<()>,
     200              : }
     201              : 
     202              : impl ThreadHandle {
     203              :     /// Create a new [`ThreadHandle`] and wait until thread will enter [`Status::Sleep`] state.
     204        19270 :     fn new(ctx: Arc<ThreadContext>, join: JoinHandle<()>) -> Self {
     205        19270 :         let mut status = ctx.mutex.lock();
     206              :         // wait until thread will go into the first yield
     207        19341 :         while *status != Status::Sleep {
     208           71 :             ctx.condvar.wait(&mut status);
     209           71 :         }
     210        19270 :         drop(status);
     211        19270 : 
     212        19270 :         Self { ctx, _join: join }
     213        19270 :     }
     214              : 
     215              :     /// Allows thread to execute one step of its execution.
     216              :     /// Returns [`Status`] of the thread after the step.
     217       283341 :     fn step(&self) -> Status {
     218       283341 :         let mut status = self.ctx.mutex.lock();
     219       283341 :         assert!(matches!(*status, Status::Sleep));
     220              : 
     221       283341 :         *status = Status::Running;
     222       283341 :         self.ctx.condvar.notify_all();
     223              : 
     224       566682 :         while *status == Status::Running {
     225       283341 :             self.ctx.condvar.wait(&mut status);
     226       283341 :         }
     227              : 
     228       283341 :         *status
     229       283341 :     }
     230              : }
     231              : 
     232              : #[derive(Clone, Copy, Debug, PartialEq, Eq)]
     233              : enum Status {
     234              :     /// Thread is running.
     235              :     Running,
     236              :     /// Waiting for event to complete, will be resumed by the executor step, once wakeup flag is set.
     237              :     Sleep,
     238              :     /// Thread finished execution.
     239              :     Finished,
     240              : }
     241              : 
     242              : const NO_WAKEUP: u8 = 0;
     243              : const PENDING_WAKEUP: u8 = 1;
     244              : 
     245              : pub struct ThreadContext {
     246              :     id: AtomicU32,
     247              :     // used to block thread until it is woken up
     248              :     mutex: parking_lot::Mutex<Status>,
     249              :     condvar: parking_lot::Condvar,
     250              :     // used as a flag to indicate runtime that thread is ready to be woken up
     251              :     wakeup: AtomicU8,
     252              :     clock: OnceLock<Arc<Timing>>,
     253              :     // execution result, set by exit() call
     254              :     result: parking_lot::Mutex<(i32, String)>,
     255              :     // determines if process should be killed on receiving panic
     256              :     allow_panic: AtomicBool,
     257              :     // acts as a signal that thread should crash itself on the next wakeup
     258              :     crash_request: AtomicBool,
     259              : }
     260              : 
     261              : impl ThreadContext {
     262        19798 :     pub(crate) fn new() -> Self {
     263        19798 :         Self {
     264        19798 :             id: AtomicU32::new(0),
     265        19798 :             mutex: parking_lot::Mutex::new(Status::Running),
     266        19798 :             condvar: parking_lot::Condvar::new(),
     267        19798 :             wakeup: AtomicU8::new(NO_WAKEUP),
     268        19798 :             clock: OnceLock::new(),
     269        19798 :             result: parking_lot::Mutex::new((-1, String::new())),
     270        19798 :             allow_panic: AtomicBool::new(false),
     271        19798 :             crash_request: AtomicBool::new(false),
     272        19798 :         }
     273        19798 :     }
     274              : }
     275              : 
     276              : // Functions for executor to control thread execution.
     277              : impl ThreadContext {
     278              :     /// Set atomic flag to indicate that thread is ready to be woken up.
     279       695545 :     fn inc_wake(&self) {
     280       695545 :         self.wakeup.store(PENDING_WAKEUP, Ordering::SeqCst);
     281       695545 :     }
     282              : 
     283              :     /// Internal function used for event queues.
     284       179554 :     pub(crate) fn schedule_wakeup(self: &Arc<Self>, after_ms: u64) {
     285       179554 :         self.clock
     286       179554 :             .get()
     287       179554 :             .unwrap()
     288       179554 :             .schedule_wakeup(after_ms, self.clone());
     289       179554 :     }
     290              : 
     291            1 :     fn tid(&self) -> u32 {
     292            1 :         self.id.load(Ordering::SeqCst)
     293            1 :     }
     294              : 
     295        19077 :     fn crash_stop(&self) {
     296        19077 :         let status = self.mutex.lock();
     297        19077 :         if *status == Status::Finished {
     298            8 :             debug!(
     299            0 :                 "trying to crash thread-{}, which is already finished",
     300            0 :                 self.tid()
     301              :             );
     302            8 :             return;
     303        19069 :         }
     304        19069 :         assert!(matches!(*status, Status::Sleep));
     305        19069 :         drop(status);
     306        19069 : 
     307        19069 :         self.allow_panic.store(true, Ordering::SeqCst);
     308        19069 :         self.crash_request.store(true, Ordering::SeqCst);
     309        19069 :         // set a wakeup
     310        19069 :         self.inc_wake();
     311              :         // it will panic on the next wakeup
     312        19077 :     }
     313              : }
     314              : 
     315              : // Internal functions.
     316              : impl ThreadContext {
     317              :     /// Blocks thread until it's woken up by the executor. If `after_ms` is 0, is will be
     318              :     /// woken on the next step. If `after_ms` > 0, wakeup is scheduled after that time.
     319              :     /// Otherwise wakeup is not scheduled inside `yield_me`, and should be arranged before
     320              :     /// calling this function.
     321       283399 :     fn yield_me(self: &Arc<Self>, after_ms: i64) {
     322       283399 :         let mut status = self.mutex.lock();
     323       283399 :         assert!(matches!(*status, Status::Running));
     324              : 
     325       283399 :         match after_ms.cmp(&0) {
     326       234726 :             std::cmp::Ordering::Less => {
     327       234726 :                 // block until something wakes us up
     328       234726 :             }
     329        20819 :             std::cmp::Ordering::Equal => {
     330        20819 :                 // tell executor that we are ready to be woken up
     331        20819 :                 self.inc_wake();
     332        20819 :             }
     333        27854 :             std::cmp::Ordering::Greater => {
     334        27854 :                 // schedule wakeup
     335        27854 :                 self.clock
     336        27854 :                     .get()
     337        27854 :                     .unwrap()
     338        27854 :                     .schedule_wakeup(after_ms as u64, self.clone());
     339        27854 :             }
     340              :         }
     341              : 
     342       283399 :         *status = Status::Sleep;
     343       283399 :         self.condvar.notify_all();
     344              : 
     345              :         // wait until executor wakes us up
     346       566798 :         while *status != Status::Running {
     347       283399 :             self.condvar.wait(&mut status);
     348       283399 :         }
     349              : 
     350       283399 :         if self.crash_request.load(Ordering::SeqCst) {
     351        18736 :             panic!("crashed by request");
     352       264663 :         }
     353       264663 :     }
     354              : 
     355              :     /// Called only once, exactly before thread finishes execution.
     356        19212 :     fn finish_me(&self) {
     357        19212 :         let mut status = self.mutex.lock();
     358        19212 :         assert!(matches!(*status, Status::Running));
     359              : 
     360        19212 :         *status = Status::Finished;
     361        19212 :         {
     362        19212 :             let mut result = self.result.lock();
     363        19212 :             if result.0 == -1 {
     364           20 :                 *result = (0, "finished normally".to_owned());
     365        19192 :             }
     366              :         }
     367        19212 :         self.condvar.notify_all();
     368        19212 :     }
     369              : }
     370              : 
     371              : /// Invokes the given closure with a reference to the current thread [`ThreadContext`].
     372              : #[inline(always)]
     373      1841235 : fn with_thread_context<T>(f: impl FnOnce(&Arc<ThreadContext>) -> T) -> T {
     374      1841235 :     thread_local!(static THREAD_DATA: Arc<ThreadContext> = Arc::new(ThreadContext::new()));
     375      1841235 :     THREAD_DATA.with(f)
     376      1841235 : }
     377              : 
     378              : /// Waker is used to wake up threads that are blocked on condition.
     379              : /// It keeps track of contexts [`Arc<ThreadContext>`] and can increment the counter
     380              : /// of several contexts to send a notification.
     381              : pub struct Waker {
     382              :     // contexts that are waiting for a notification
     383              :     contexts: parking_lot::Mutex<smallvec::SmallVec<[Arc<ThreadContext>; 8]>>,
     384              : }
     385              : 
     386              : impl Default for Waker {
     387            0 :     fn default() -> Self {
     388            0 :         Self::new()
     389            0 :     }
     390              : }
     391              : 
     392              : impl Waker {
     393        78013 :     pub fn new() -> Self {
     394        78013 :         Self {
     395        78013 :             contexts: parking_lot::Mutex::new(smallvec::SmallVec::new()),
     396        78013 :         }
     397        78013 :     }
     398              : 
     399              :     /// Subscribe current thread to receive a wake notification later.
     400       810419 :     pub fn wake_me_later(&self) {
     401       810419 :         with_thread_context(|ctx| {
     402       810419 :             self.contexts.lock().push(ctx.clone());
     403       810419 :         });
     404       810419 :     }
     405              : 
     406              :     /// Wake up all threads that are waiting for a notification and clear the list.
     407       123670 :     pub fn wake_all(&self) {
     408       123670 :         let mut v = self.contexts.lock();
     409       438905 :         for ctx in v.iter() {
     410       438905 :             ctx.inc_wake();
     411       438905 :         }
     412       123670 :         v.clear();
     413       123670 :     }
     414              : }
     415              : 
     416              : /// See [`ThreadContext::yield_me`].
     417       264129 : pub fn yield_me(after_ms: i64) {
     418       264129 :     with_thread_context(|ctx| ctx.yield_me(after_ms))
     419       264129 : }
     420              : 
     421              : /// Get current time.
     422       708029 : pub fn now() -> u64 {
     423       708029 :     with_thread_context(|ctx| ctx.clock.get().unwrap().now())
     424       708029 : }
     425              : 
     426          456 : pub fn exit(code: i32, msg: String) {
     427          456 :     with_thread_context(|ctx| {
     428          456 :         ctx.allow_panic.store(true, Ordering::SeqCst);
     429          456 :         let mut result = ctx.result.lock();
     430          456 :         *result = (code, msg);
     431          456 :         panic!("exit");
     432          456 :     });
     433          456 : }
     434              : 
     435          528 : pub(crate) fn get_thread_ctx() -> Arc<ThreadContext> {
     436          528 :     with_thread_context(|ctx| ctx.clone())
     437          528 : }
     438              : 
     439              : /// Trait for polling channels until they have something.
     440              : pub trait PollSome {
     441              :     /// Schedule wakeup for message arrival.
     442              :     fn wake_me(&self);
     443              : 
     444              :     /// Check if channel has a ready message.
     445              :     fn has_some(&self) -> bool;
     446              : }
     447              : 
     448              : /// Blocks current thread until one of the channels has a ready message. Returns
     449              : /// index of the channel that has a message. If timeout is reached, returns None.
     450              : ///
     451              : /// Negative timeout means block forever. Zero timeout means check channels and return
     452              : /// immediately. Positive timeout means block until timeout is reached.
     453       103827 : pub fn epoll_chans(chans: &[Box<dyn PollSome>], timeout: i64) -> Option<usize> {
     454       103827 :     let deadline = if timeout < 0 {
     455        75943 :         0
     456              :     } else {
     457        27884 :         now() + timeout as u64
     458              :     };
     459              : 
     460              :     loop {
     461      1004591 :         for chan in chans {
     462       807544 :             chan.wake_me()
     463              :         }
     464              : 
     465       653896 :         for (i, chan) in chans.iter().enumerate() {
     466       653896 :             if chan.has_some() {
     467        83342 :                 return Some(i);
     468       570554 :             }
     469              :         }
     470              : 
     471        95850 :         if timeout < 0 {
     472        65366 :             // block until wakeup
     473        65366 :             yield_me(-1);
     474        65366 :         } else {
     475        30484 :             let current_time = now();
     476        30484 :             if current_time >= deadline {
     477         2630 :                 return None;
     478        27854 :             }
     479        27854 : 
     480        27854 :             yield_me((deadline - current_time) as i64);
     481              :         }
     482              :     }
     483        85972 : }
        

Generated by: LCOV version 2.1-beta