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

Generated by: LCOV version 2.1-beta