LCOV - code coverage report
Current view: top level - libs/desim/src - executor.rs (source / functions) Coverage Total Hit
Test: 02e8c57acd6e2b986849f552ca30280d54699b79.info Lines: 96.8 % 281 272
Test Date: 2024-06-26 17:13:54 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         4056 :     pub fn new(clock: Arc<Timing>) -> Self {
      32         4056 :         Self {
      33         4056 :             threads: Vec::new(),
      34         4056 :             clock,
      35         4056 :             thread_counter: AtomicU32::new(0),
      36         4056 :             step_counter: 0,
      37         4056 :         }
      38         4056 :     }
      39              : 
      40              :     /// Spawn a new thread and register it in the runtime.
      41       155227 :     pub fn spawn<F>(&mut self, f: F) -> ExternalHandle
      42       155227 :     where
      43       155227 :         F: FnOnce() + Send + 'static,
      44       155227 :     {
      45       155227 :         let (tx, rx) = mpsc::channel();
      46       155227 : 
      47       155227 :         let clock = self.clock.clone();
      48       155227 :         let tid = self.thread_counter.fetch_add(1, Ordering::SeqCst);
      49       155227 :         debug!("spawning thread-{}", tid);
      50              : 
      51       155227 :         let join = std::thread::spawn(move || {
      52       155227 :             let _guard = tracing::info_span!("", tid).entered();
      53       155227 : 
      54       155227 :             let res = std::panic::catch_unwind(AssertUnwindSafe(|| {
      55       155227 :                 with_thread_context(|ctx| {
      56       155227 :                     assert!(ctx.clock.set(clock).is_ok());
      57       155227 :                     ctx.id.store(tid, Ordering::SeqCst);
      58       155227 :                     tx.send(ctx.clone()).expect("failed to send thread context");
      59       155227 :                     // suspend thread to put it to `threads` in sleeping state
      60       155227 :                     ctx.yield_me(0);
      61       155227 :                 });
      62       155227 : 
      63       155227 :                 // start user-provided function
      64       155227 :                 f();
      65       155227 :             }));
      66       155227 :             debug!("thread finished");
      67              : 
      68       155111 :             if let Err(e) = res {
      69       155071 :                 with_thread_context(|ctx| {
      70       155071 :                     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       155071 :                     }
      74       155071 : 
      75       155071 :                     debug!("thread panicked: {:?}", e);
      76       155071 :                     let mut result = ctx.result.lock();
      77       155071 :                     if result.0 == -1 {
      78       151820 :                         *result = (256, format!("thread panicked: {:?}", e));
      79       151820 :                     }
      80       155071 :                 });
      81       155071 :             }
      82              : 
      83       155111 :             with_thread_context(|ctx| {
      84       155111 :                 ctx.finish_me();
      85       155111 :             });
      86       155227 :         });
      87       155227 : 
      88       155227 :         let ctx = rx.recv().expect("failed to receive thread context");
      89       155227 :         let handle = ThreadHandle::new(ctx.clone(), join);
      90       155227 : 
      91       155227 :         self.threads.push(handle);
      92       155227 : 
      93       155227 :         ExternalHandle { ctx }
      94       155227 :     }
      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      3128645 :     pub fn step(&mut self) -> bool {
      99      3128645 :         trace!("runtime step");
     100              : 
     101              :         // have we run any thread?
     102      3128645 :         let mut ran = false;
     103      3128645 : 
     104     15707712 :         self.threads.retain(|thread: &ThreadHandle| {
     105     15707712 :             let res = thread.ctx.wakeup.compare_exchange(
     106     15707712 :                 PENDING_WAKEUP,
     107     15707712 :                 NO_WAKEUP,
     108     15707712 :                 Ordering::SeqCst,
     109     15707712 :                 Ordering::SeqCst,
     110     15707712 :             );
     111     15707712 :             if res.is_err() {
     112              :                 // thread has no pending wakeups, leaving as is
     113     13561195 :                 return true;
     114      2146517 :             }
     115      2146517 :             ran = true;
     116      2146517 : 
     117      2146517 :             trace!("entering thread-{}", thread.ctx.tid());
     118      2146517 :             let status = thread.step();
     119      2146517 :             self.step_counter += 1;
     120      2146517 :             trace!(
     121            0 :                 "out of thread-{} with status {:?}",
     122            0 :                 thread.ctx.tid(),
     123              :                 status
     124              :             );
     125              : 
     126      2146517 :             if status == Status::Sleep {
     127      1991406 :                 true
     128              :             } else {
     129       155111 :                 trace!("thread has finished");
     130              :                 // removing the thread from the list
     131       155111 :                 false
     132              :             }
     133     15707712 :         });
     134      3128645 : 
     135      3128645 :         if !ran {
     136      1658301 :             trace!("no threads were run, stepping clock");
     137      1658301 :             if let Some(ctx_to_wake) = self.clock.step() {
     138      1654205 :                 trace!("waking up thread-{}", ctx_to_wake.tid());
     139      1654205 :                 ctx_to_wake.inc_wake();
     140              :             } else {
     141         4096 :                 return false;
     142              :             }
     143      1470344 :         }
     144              : 
     145      3124549 :         true
     146      3128645 :     }
     147              : 
     148              :     /// Kill all threads. This is done by setting a flag in each thread context and waking it up.
     149         8016 :     pub fn crash_all_threads(&mut self) {
     150        22695 :         for thread in self.threads.iter() {
     151        22695 :             thread.ctx.crash_stop();
     152        22695 :         }
     153              : 
     154              :         // all threads should be finished after a few steps
     155        12024 :         while !self.threads.is_empty() {
     156         4008 :             self.step();
     157         4008 :         }
     158         8016 :     }
     159              : }
     160              : 
     161              : impl Drop for Runtime {
     162         4006 :     fn drop(&mut self) {
     163         4006 :         debug!("dropping the runtime");
     164         4006 :         self.crash_all_threads();
     165         4006 :     }
     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      3298536 :     pub fn is_finished(&self) -> bool {
     176      3298536 :         let status = self.ctx.mutex.lock();
     177      3298536 :         *status == Status::Finished
     178      3298536 :     }
     179              : 
     180              :     /// Returns exitcode and message, which is available after thread has finished execution.
     181         3168 :     pub fn result(&self) -> (i32, String) {
     182         3168 :         let result = self.ctx.result.lock();
     183         3168 :         result.clone()
     184         3168 :     }
     185              : 
     186              :     /// Returns thread id.
     187           28 :     pub fn id(&self) -> u32 {
     188           28 :         self.ctx.id.load(Ordering::SeqCst)
     189           28 :     }
     190              : 
     191              :     /// Sets a flag to crash thread on the next wakeup.
     192       131863 :     pub fn crash_stop(&self) {
     193       131863 :         self.ctx.crash_stop();
     194       131863 :     }
     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       155227 :     fn new(ctx: Arc<ThreadContext>, join: JoinHandle<()>) -> Self {
     205       155227 :         let mut status = ctx.mutex.lock();
     206              :         // wait until thread will go into the first yield
     207       176321 :         while *status != Status::Sleep {
     208        21094 :             ctx.condvar.wait(&mut status);
     209        21094 :         }
     210       155227 :         drop(status);
     211       155227 : 
     212       155227 :         Self { ctx, _join: join }
     213       155227 :     }
     214              : 
     215              :     /// Allows thread to execute one step of its execution.
     216              :     /// Returns [`Status`] of the thread after the step.
     217      2146517 :     fn step(&self) -> Status {
     218      2146517 :         let mut status = self.ctx.mutex.lock();
     219      2146517 :         assert!(matches!(*status, Status::Sleep));
     220              : 
     221      2146517 :         *status = Status::Running;
     222      2146517 :         self.ctx.condvar.notify_all();
     223              : 
     224      4293034 :         while *status == Status::Running {
     225      2146517 :             self.ctx.condvar.wait(&mut status);
     226      2146517 :         }
     227              : 
     228      2146517 :         *status
     229      2146517 :     }
     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       159283 :     pub(crate) fn new() -> Self {
     263       159283 :         Self {
     264       159283 :             id: AtomicU32::new(0),
     265       159283 :             mutex: parking_lot::Mutex::new(Status::Running),
     266       159283 :             condvar: parking_lot::Condvar::new(),
     267       159283 :             wakeup: AtomicU8::new(NO_WAKEUP),
     268       159283 :             clock: OnceLock::new(),
     269       159283 :             result: parking_lot::Mutex::new((-1, String::new())),
     270       159283 :             allow_panic: AtomicBool::new(false),
     271       159283 :             crash_request: AtomicBool::new(false),
     272       159283 :         }
     273       159283 :     }
     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      5166641 :     fn inc_wake(&self) {
     280      5166641 :         self.wakeup.store(PENDING_WAKEUP, Ordering::SeqCst);
     281      5166641 :     }
     282              : 
     283              :     /// Internal function used for event queues.
     284      1349185 :     pub(crate) fn schedule_wakeup(self: &Arc<Self>, after_ms: u64) {
     285      1349185 :         self.clock
     286      1349185 :             .get()
     287      1349185 :             .unwrap()
     288      1349185 :             .schedule_wakeup(after_ms, self.clone());
     289      1349185 :     }
     290              : 
     291            2 :     fn tid(&self) -> u32 {
     292            2 :         self.id.load(Ordering::SeqCst)
     293            2 :     }
     294              : 
     295       154558 :     fn crash_stop(&self) {
     296       154558 :         let status = self.mutex.lock();
     297       154558 :         if *status == Status::Finished {
     298           79 :             debug!(
     299            0 :                 "trying to crash thread-{}, which is already finished",
     300            0 :                 self.tid()
     301              :             );
     302           79 :             return;
     303       154479 :         }
     304       154479 :         assert!(matches!(*status, Status::Sleep));
     305       154479 :         drop(status);
     306       154479 : 
     307       154479 :         self.allow_panic.store(true, Ordering::SeqCst);
     308       154479 :         self.crash_request.store(true, Ordering::SeqCst);
     309       154479 :         // set a wakeup
     310       154479 :         self.inc_wake();
     311              :         // it will panic on the next wakeup
     312       154558 :     }
     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      2146633 :     fn yield_me(self: &Arc<Self>, after_ms: i64) {
     322      2146633 :         let mut status = self.mutex.lock();
     323      2146633 :         assert!(matches!(*status, Status::Running));
     324              : 
     325      2146633 :         match after_ms.cmp(&0) {
     326      1778118 :             std::cmp::Ordering::Less => {
     327      1778118 :                 // block until something wakes us up
     328      1778118 :             }
     329       159858 :             std::cmp::Ordering::Equal => {
     330       159858 :                 // tell executor that we are ready to be woken up
     331       159858 :                 self.inc_wake();
     332       159858 :             }
     333       208657 :             std::cmp::Ordering::Greater => {
     334       208657 :                 // schedule wakeup
     335       208657 :                 self.clock
     336       208657 :                     .get()
     337       208657 :                     .unwrap()
     338       208657 :                     .schedule_wakeup(after_ms as u64, self.clone());
     339       208657 :             }
     340              :         }
     341              : 
     342      2146633 :         *status = Status::Sleep;
     343      2146633 :         self.condvar.notify_all();
     344              : 
     345              :         // wait until executor wakes us up
     346      4293266 :         while *status != Status::Running {
     347      2146633 :             self.condvar.wait(&mut status);
     348      2146633 :         }
     349              : 
     350      2146633 :         if self.crash_request.load(Ordering::SeqCst) {
     351       151820 :             panic!("crashed by request");
     352      1994813 :         }
     353      1994813 :     }
     354              : 
     355              :     /// Called only once, exactly before thread finishes execution.
     356       155111 :     fn finish_me(&self) {
     357       155111 :         let mut status = self.mutex.lock();
     358       155111 :         assert!(matches!(*status, Status::Running));
     359              : 
     360       155111 :         *status = Status::Finished;
     361       155111 :         {
     362       155111 :             let mut result = self.result.lock();
     363       155111 :             if result.0 == -1 {
     364           40 :                 *result = (0, "finished normally".to_owned());
     365       155071 :             }
     366              :         }
     367       155111 :         self.condvar.notify_all();
     368       155111 :     }
     369              : }
     370              : 
     371              : /// Invokes the given closure with a reference to the current thread [`ThreadContext`].
     372              : #[inline(always)]
     373     13881928 : fn with_thread_context<T>(f: impl FnOnce(&Arc<ThreadContext>) -> T) -> T {
     374     13881928 :     thread_local!(static THREAD_DATA: Arc<ThreadContext> = Arc::new(ThreadContext::new()));
     375     13881928 :     THREAD_DATA.with(f)
     376     13881928 : }
     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       623062 :     pub fn new() -> Self {
     394       623062 :         Self {
     395       623062 :             contexts: parking_lot::Mutex::new(smallvec::SmallVec::new()),
     396       623062 :         }
     397       623062 :     }
     398              : 
     399              :     /// Subscribe current thread to receive a wake notification later.
     400      6054677 :     pub fn wake_me_later(&self) {
     401      6054677 :         with_thread_context(|ctx| {
     402      6054677 :             self.contexts.lock().push(ctx.clone());
     403      6054677 :         });
     404      6054677 :     }
     405              : 
     406              :     /// Wake up all threads that are waiting for a notification and clear the list.
     407       940087 :     pub fn wake_all(&self) {
     408       940087 :         let mut v = self.contexts.lock();
     409      3198099 :         for ctx in v.iter() {
     410      3198099 :             ctx.inc_wake();
     411      3198099 :         }
     412       940087 :         v.clear();
     413       940087 :     }
     414              : }
     415              : 
     416              : /// See [`ThreadContext::yield_me`].
     417      1991406 : pub fn yield_me(after_ms: i64) {
     418      1991406 :     with_thread_context(|ctx| ctx.yield_me(after_ms))
     419      1991406 : }
     420              : 
     421              : /// Get current time.
     422      5363129 : pub fn now() -> u64 {
     423      5363129 :     with_thread_context(|ctx| ctx.clock.get().unwrap().now())
     424      5363129 : }
     425              : 
     426         3251 : pub fn exit(code: i32, msg: String) {
     427         3251 :     with_thread_context(|ctx| {
     428         3251 :         ctx.allow_panic.store(true, Ordering::SeqCst);
     429         3251 :         let mut result = ctx.result.lock();
     430         3251 :         *result = (code, msg);
     431         3251 :         panic!("exit");
     432         3251 :     });
     433         3251 : }
     434              : 
     435         4056 : pub(crate) fn get_thread_ctx() -> Arc<ThreadContext> {
     436         4056 :     with_thread_context(|ctx| ctx.clone())
     437         4056 : }
     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       802300 : pub fn epoll_chans(chans: &[Box<dyn PollSome>], timeout: i64) -> Option<usize> {
     454       802300 :     let deadline = if timeout < 0 {
     455       587449 :         0
     456              :     } else {
     457       214851 :         now() + timeout as u64
     458              :     };
     459              : 
     460              :     loop {
     461      7561006 :         for chan in chans {
     462      6045007 :             chan.wake_me()
     463              :         }
     464              : 
     465      4862577 :         for (i, chan) in chans.iter().enumerate() {
     466      4862577 :             if chan.has_some() {
     467       635898 :                 return Some(i);
     468      4226679 :             }
     469              :         }
     470              : 
     471       735483 :         if timeout < 0 {
     472       505042 :             // block until wakeup
     473       505042 :             yield_me(-1);
     474       505042 :         } else {
     475       230441 :             let current_time = now();
     476       230441 :             if current_time >= deadline {
     477        21784 :                 return None;
     478       208657 :             }
     479       208657 : 
     480       208657 :             yield_me((deadline - current_time) as i64);
     481              :         }
     482              :     }
     483       657682 : }
        

Generated by: LCOV version 2.1-beta