1 //! Implements threads.
3 use std::cell::RefCell;
4 use std::collections::hash_map::Entry;
5 use std::num::TryFromIntError;
6 use std::time::{Duration, Instant, SystemTime};
10 use rustc_data_structures::fx::FxHashMap;
11 use rustc_hir::def_id::DefId;
12 use rustc_index::vec::{Idx, IndexVec};
13 use rustc_middle::mir::Mutability;
15 use crate::concurrency::data_race;
16 use crate::sync::SynchronizationState;
19 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
20 pub enum SchedulingAction {
21 /// Execute step on the active thread.
23 /// Execute a timeout callback.
24 ExecuteTimeoutCallback,
25 /// Execute destructors of the active thread.
31 /// Timeout callbacks can be created by synchronization primitives to tell the
32 /// scheduler that they should be called once some period of time passes.
33 type TimeoutCallback<'mir, 'tcx> =
34 Box<dyn FnOnce(&mut InterpCx<'mir, 'tcx, Evaluator<'mir, 'tcx>>) -> InterpResult<'tcx> + 'tcx>;
36 /// A thread identifier.
37 #[derive(Clone, Copy, Debug, PartialOrd, Ord, PartialEq, Eq, Hash)]
38 pub struct ThreadId(u32);
40 /// The main thread. When it terminates, the whole application terminates.
41 const MAIN_THREAD: ThreadId = ThreadId(0);
44 pub fn to_u32(self) -> u32 {
49 impl Idx for ThreadId {
50 fn new(idx: usize) -> Self {
51 ThreadId(u32::try_from(idx).unwrap())
54 fn index(self) -> usize {
55 usize::try_from(self.0).unwrap()
59 impl TryFrom<u64> for ThreadId {
60 type Error = TryFromIntError;
61 fn try_from(id: u64) -> Result<Self, Self::Error> {
62 u32::try_from(id).map(Self)
66 impl From<u32> for ThreadId {
67 fn from(id: u32) -> Self {
73 pub fn to_u32_scalar(&self) -> Scalar<Tag> {
74 Scalar::from_u32(self.0)
78 /// The state of a thread.
79 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
80 pub enum ThreadState {
81 /// The thread is enabled and can be executed.
83 /// The thread tried to join the specified thread and is blocked until that
84 /// thread terminates.
85 BlockedOnJoin(ThreadId),
86 /// The thread is blocked on some synchronization primitive. It is the
87 /// responsibility of the synchronization primitives to track threads that
88 /// are blocked by them.
90 /// The thread has terminated its execution. We do not delete terminated
91 /// threads (FIXME: why?).
95 /// The join status of a thread.
96 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
97 enum ThreadJoinStatus {
98 /// The thread can be joined.
100 /// A thread is detached if its join handle was destroyed and no other
101 /// thread can join it.
103 /// The thread was already joined by some thread and cannot be joined again.
108 pub struct Thread<'mir, 'tcx> {
111 /// Name of the thread.
112 thread_name: Option<Vec<u8>>,
114 /// The virtual call stack.
115 stack: Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>>,
118 join_status: ThreadJoinStatus,
120 /// The temporary used for storing the argument of
121 /// the call to `miri_start_panic` (the panic payload) when unwinding.
122 /// This is pointer-sized, and matches the `Payload` type in `src/libpanic_unwind/miri.rs`.
123 pub(crate) panic_payload: Option<Scalar<Tag>>,
125 /// Last OS error location in memory. It is a 32-bit integer.
126 pub(crate) last_error: Option<MPlaceTy<'tcx, Tag>>,
129 impl<'mir, 'tcx> Thread<'mir, 'tcx> {
130 /// Check if the thread is done executing (no more stack frames). If yes,
131 /// change the state to terminated and return `true`.
132 fn check_terminated(&mut self) -> bool {
133 if self.state == ThreadState::Enabled {
134 if self.stack.is_empty() {
135 self.state = ThreadState::Terminated;
142 /// Get the name of the current thread, or `<unnamed>` if it was not set.
143 fn thread_name(&self) -> &[u8] {
144 if let Some(ref thread_name) = self.thread_name { thread_name } else { b"<unnamed>" }
148 impl<'mir, 'tcx> std::fmt::Debug for Thread<'mir, 'tcx> {
149 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
153 String::from_utf8_lossy(self.thread_name()),
160 impl<'mir, 'tcx> Default for Thread<'mir, 'tcx> {
161 fn default() -> Self {
163 state: ThreadState::Enabled,
166 join_status: ThreadJoinStatus::Joinable,
173 impl<'mir, 'tcx> Thread<'mir, 'tcx> {
174 fn new(name: &str) -> Self {
175 let mut thread = Thread::default();
176 thread.thread_name = Some(Vec::from(name.as_bytes()));
181 /// A specific moment in time.
185 RealTime(SystemTime),
189 /// How long do we have to wait from now until the specified time?
190 fn get_wait_time(&self) -> Duration {
192 Time::Monotonic(instant) => instant.saturating_duration_since(Instant::now()),
193 Time::RealTime(time) =>
194 time.duration_since(SystemTime::now()).unwrap_or(Duration::new(0, 0)),
199 /// Callbacks are used to implement timeouts. For example, waiting on a
200 /// conditional variable with a timeout creates a callback that is called after
201 /// the specified time and unblocks the thread. If another thread signals on the
202 /// conditional variable, the signal handler deletes the callback.
203 struct TimeoutCallbackInfo<'mir, 'tcx> {
204 /// The callback should be called no earlier than this time.
206 /// The called function.
207 callback: TimeoutCallback<'mir, 'tcx>,
210 impl<'mir, 'tcx> std::fmt::Debug for TimeoutCallbackInfo<'mir, 'tcx> {
211 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
212 write!(f, "TimeoutCallback({:?})", self.call_time)
216 /// A set of threads.
218 pub struct ThreadManager<'mir, 'tcx> {
219 /// Identifier of the currently active thread.
220 active_thread: ThreadId,
221 /// Threads used in the program.
223 /// Note that this vector also contains terminated threads.
224 threads: IndexVec<ThreadId, Thread<'mir, 'tcx>>,
225 /// This field is pub(crate) because the synchronization primitives
226 /// (`crate::sync`) need a way to access it.
227 pub(crate) sync: SynchronizationState,
228 /// A mapping from a thread-local static to an allocation id of a thread
229 /// specific allocation.
230 thread_local_alloc_ids: RefCell<FxHashMap<(DefId, ThreadId), Pointer<Tag>>>,
231 /// A flag that indicates that we should change the active thread.
232 yield_active_thread: bool,
233 /// Callbacks that are called once the specified time passes.
234 timeout_callbacks: FxHashMap<ThreadId, TimeoutCallbackInfo<'mir, 'tcx>>,
237 impl<'mir, 'tcx> Default for ThreadManager<'mir, 'tcx> {
238 fn default() -> Self {
239 let mut threads = IndexVec::new();
240 // Create the main thread and add it to the list of threads.
241 let mut main_thread = Thread::new("main");
242 // The main thread can *not* be joined on.
243 main_thread.join_status = ThreadJoinStatus::Detached;
244 threads.push(main_thread);
246 active_thread: ThreadId::new(0),
248 sync: SynchronizationState::default(),
249 thread_local_alloc_ids: Default::default(),
250 yield_active_thread: false,
251 timeout_callbacks: FxHashMap::default(),
256 impl<'mir, 'tcx: 'mir> ThreadManager<'mir, 'tcx> {
257 /// Check if we have an allocation for the given thread local static for the
259 fn get_thread_local_alloc_id(&self, def_id: DefId) -> Option<Pointer<Tag>> {
260 self.thread_local_alloc_ids.borrow().get(&(def_id, self.active_thread)).cloned()
263 /// Set the pointer for the allocation of the given thread local
264 /// static for the active thread.
266 /// Panics if a thread local is initialized twice for the same thread.
267 fn set_thread_local_alloc(&self, def_id: DefId, ptr: Pointer<Tag>) {
268 self.thread_local_alloc_ids
270 .try_insert((def_id, self.active_thread), ptr)
274 /// Borrow the stack of the active thread.
275 pub fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
276 &self.threads[self.active_thread].stack
279 /// Mutably borrow the stack of the active thread.
280 fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
281 &mut self.threads[self.active_thread].stack
284 pub fn all_stacks(&self) -> impl Iterator<Item = &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>]> {
285 self.threads.iter().map(|t| &t.stack[..])
288 /// Create a new thread and returns its id.
289 fn create_thread(&mut self) -> ThreadId {
290 let new_thread_id = ThreadId::new(self.threads.len());
291 self.threads.push(Default::default());
295 /// Set an active thread and return the id of the thread that was active before.
296 fn set_active_thread_id(&mut self, id: ThreadId) -> ThreadId {
297 let active_thread_id = self.active_thread;
298 self.active_thread = id;
299 assert!(self.active_thread.index() < self.threads.len());
303 /// Get the id of the currently active thread.
304 pub fn get_active_thread_id(&self) -> ThreadId {
308 /// Get the total number of threads that were ever spawn by this program.
309 pub fn get_total_thread_count(&self) -> usize {
313 /// Get the total of threads that are currently live, i.e., not yet terminated.
314 /// (They might be blocked.)
315 pub fn get_live_thread_count(&self) -> usize {
316 self.threads.iter().filter(|t| !matches!(t.state, ThreadState::Terminated)).count()
319 /// Has the given thread terminated?
320 fn has_terminated(&self, thread_id: ThreadId) -> bool {
321 self.threads[thread_id].state == ThreadState::Terminated
324 /// Have all threads terminated?
325 fn have_all_terminated(&self) -> bool {
326 self.threads.iter().all(|thread| thread.state == ThreadState::Terminated)
329 /// Enable the thread for execution. The thread must be terminated.
330 fn enable_thread(&mut self, thread_id: ThreadId) {
331 assert!(self.has_terminated(thread_id));
332 self.threads[thread_id].state = ThreadState::Enabled;
335 /// Get a mutable borrow of the currently active thread.
336 fn active_thread_mut(&mut self) -> &mut Thread<'mir, 'tcx> {
337 &mut self.threads[self.active_thread]
340 /// Get a shared borrow of the currently active thread.
341 fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
342 &self.threads[self.active_thread]
345 /// Mark the thread as detached, which means that no other thread will try
346 /// to join it and the thread is responsible for cleaning up.
347 fn detach_thread(&mut self, id: ThreadId) -> InterpResult<'tcx> {
348 if self.threads[id].join_status != ThreadJoinStatus::Joinable {
349 throw_ub_format!("trying to detach thread that was already detached or joined");
351 self.threads[id].join_status = ThreadJoinStatus::Detached;
355 /// Mark that the active thread tries to join the thread with `joined_thread_id`.
358 joined_thread_id: ThreadId,
359 data_race: Option<&mut data_race::GlobalState>,
360 ) -> InterpResult<'tcx> {
361 if self.threads[joined_thread_id].join_status != ThreadJoinStatus::Joinable {
362 throw_ub_format!("trying to join a detached or already joined thread");
364 if joined_thread_id == self.active_thread {
365 throw_ub_format!("trying to join itself");
370 .all(|thread| thread.state != ThreadState::BlockedOnJoin(joined_thread_id)),
371 "a joinable thread already has threads waiting for its termination"
373 // Mark the joined thread as being joined so that we detect if other
374 // threads try to join it.
375 self.threads[joined_thread_id].join_status = ThreadJoinStatus::Joined;
376 if self.threads[joined_thread_id].state != ThreadState::Terminated {
377 // The joined thread is still running, we need to wait for it.
378 self.active_thread_mut().state = ThreadState::BlockedOnJoin(joined_thread_id);
380 "{:?} blocked on {:?} when trying to join",
385 // The thread has already terminated - mark join happens-before
386 if let Some(data_race) = data_race {
387 data_race.thread_joined(self, self.active_thread, joined_thread_id);
393 /// Set the name of the active thread.
394 fn set_active_thread_name(&mut self, new_thread_name: Vec<u8>) {
395 self.active_thread_mut().thread_name = Some(new_thread_name);
398 /// Get the name of the active thread.
399 pub fn get_active_thread_name(&self) -> &[u8] {
400 self.active_thread_ref().thread_name()
403 /// Get the name of the given thread.
404 pub fn get_thread_name(&self, thread: ThreadId) -> &[u8] {
405 self.threads[thread].thread_name()
408 /// Put the thread into the blocked state.
409 fn block_thread(&mut self, thread: ThreadId) {
410 let state = &mut self.threads[thread].state;
411 assert_eq!(*state, ThreadState::Enabled);
412 *state = ThreadState::BlockedOnSync;
415 /// Put the blocked thread into the enabled state.
416 fn unblock_thread(&mut self, thread: ThreadId) {
417 let state = &mut self.threads[thread].state;
418 assert_eq!(*state, ThreadState::BlockedOnSync);
419 *state = ThreadState::Enabled;
422 /// Change the active thread to some enabled thread.
423 fn yield_active_thread(&mut self) {
424 // We do not yield immediately, as swapping out the current stack while executing a MIR statement
425 // could lead to all sorts of confusion.
426 // We should only switch stacks between steps.
427 self.yield_active_thread = true;
430 /// Register the given `callback` to be called once the `call_time` passes.
432 /// The callback will be called with `thread` being the active thread, and
433 /// the callback may not change the active thread.
434 fn register_timeout_callback(
438 callback: TimeoutCallback<'mir, 'tcx>,
440 self.timeout_callbacks
441 .try_insert(thread, TimeoutCallbackInfo { call_time, callback })
445 /// Unregister the callback for the `thread`.
446 fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
447 self.timeout_callbacks.remove(&thread);
450 /// Get a callback that is ready to be called.
451 fn get_ready_callback(&mut self) -> Option<(ThreadId, TimeoutCallback<'mir, 'tcx>)> {
452 // We iterate over all threads in the order of their indices because
453 // this allows us to have a deterministic scheduler.
454 for thread in self.threads.indices() {
455 match self.timeout_callbacks.entry(thread) {
456 Entry::Occupied(entry) =>
457 if entry.get().call_time.get_wait_time() == Duration::new(0, 0) {
458 return Some((thread, entry.remove().callback));
460 Entry::Vacant(_) => {}
466 /// Wakes up threads joining on the active one and deallocates thread-local statics.
467 /// The `AllocId` that can now be freed are returned.
468 fn thread_terminated(
470 mut data_race: Option<&mut data_race::GlobalState>,
471 ) -> Vec<Pointer<Tag>> {
472 let mut free_tls_statics = Vec::new();
474 let mut thread_local_statics = self.thread_local_alloc_ids.borrow_mut();
475 thread_local_statics.retain(|&(_def_id, thread), &mut alloc_id| {
476 if thread != self.active_thread {
477 // Keep this static around.
480 // Delete this static from the map and from memory.
481 // We cannot free directly here as we cannot use `?` in this context.
482 free_tls_statics.push(alloc_id);
486 // Set the thread into a terminated state in the data-race detector.
487 if let Some(ref mut data_race) = data_race {
488 data_race.thread_terminated(self);
490 // Check if we need to unblock any threads.
491 let mut joined_threads = vec![]; // store which threads joined, we'll need it
492 for (i, thread) in self.threads.iter_enumerated_mut() {
493 if thread.state == ThreadState::BlockedOnJoin(self.active_thread) {
494 // The thread has terminated, mark happens-before edge to joining thread
495 if data_race.is_some() {
496 joined_threads.push(i);
498 trace!("unblocking {:?} because {:?} terminated", i, self.active_thread);
499 thread.state = ThreadState::Enabled;
502 for &i in &joined_threads {
503 data_race.as_mut().unwrap().thread_joined(self, i, self.active_thread);
508 /// Decide which action to take next and on which thread.
510 /// The currently implemented scheduling policy is the one that is commonly
511 /// used in stateless model checkers such as Loom: run the active thread as
512 /// long as we can and switch only when we have to (the active thread was
513 /// blocked, terminated, or has explicitly asked to be preempted).
514 fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
515 // Check whether the thread has **just** terminated (`check_terminated`
516 // checks whether the thread has popped all its stack and if yes, sets
517 // the thread state to terminated).
518 if self.threads[self.active_thread].check_terminated() {
519 return Ok(SchedulingAction::ExecuteDtors);
521 // If we get here again and the thread is *still* terminated, there are no more dtors to run.
522 if self.threads[MAIN_THREAD].state == ThreadState::Terminated {
523 // The main thread terminated; stop the program.
524 // We do *not* run TLS dtors of remaining threads, which seems to match rustc behavior.
525 return Ok(SchedulingAction::Stop);
527 // This thread and the program can keep going.
528 if self.threads[self.active_thread].state == ThreadState::Enabled
529 && !self.yield_active_thread
531 // The currently active thread is still enabled, just continue with it.
532 return Ok(SchedulingAction::ExecuteStep);
534 // The active thread yielded. Let's see if there are any timeouts to take care of. We do
535 // this *before* running any other thread, to ensure that timeouts "in the past" fire before
536 // any other thread can take an action. This ensures that for `pthread_cond_timedwait`, "an
537 // error is returned if [...] the absolute time specified by abstime has already been passed
538 // at the time of the call".
539 // <https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html>
540 let potential_sleep_time =
541 self.timeout_callbacks.values().map(|info| info.call_time.get_wait_time()).min();
542 if potential_sleep_time == Some(Duration::new(0, 0)) {
543 return Ok(SchedulingAction::ExecuteTimeoutCallback);
545 // No callbacks scheduled, pick a regular thread to execute.
546 // The active thread blocked or yielded. So we go search for another enabled thread.
547 // Curcially, we start searching at the current active thread ID, rather than at 0, since we
548 // want to avoid always scheduling threads 0 and 1 without ever making progress in thread 2.
550 // `skip(N)` means we start iterating at thread N, so we skip 1 more to start just *after*
551 // the active thread. Then after that we look at `take(N)`, i.e., the threads *before* the
556 .skip(self.active_thread.index() + 1)
557 .chain(self.threads.iter_enumerated().take(self.active_thread.index()));
558 for (id, thread) in threads {
559 debug_assert_ne!(self.active_thread, id);
560 if thread.state == ThreadState::Enabled {
561 self.active_thread = id;
565 self.yield_active_thread = false;
566 if self.threads[self.active_thread].state == ThreadState::Enabled {
567 return Ok(SchedulingAction::ExecuteStep);
569 // We have not found a thread to execute.
570 if self.threads.iter().all(|thread| thread.state == ThreadState::Terminated) {
571 unreachable!("all threads terminated without the main thread terminating?!");
572 } else if let Some(sleep_time) = potential_sleep_time {
573 // All threads are currently blocked, but we have unexecuted
574 // timeout_callbacks, which may unblock some of the threads. Hence,
575 // sleep until the first callback.
576 std::thread::sleep(sleep_time);
577 Ok(SchedulingAction::ExecuteTimeoutCallback)
579 throw_machine_stop!(TerminationInfo::Deadlock);
584 // Public interface to thread management.
585 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
586 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
587 /// Get a thread-specific allocation id for the given thread-local static.
588 /// If needed, allocate a new one.
589 fn get_or_create_thread_local_alloc(
592 ) -> InterpResult<'tcx, Pointer<Tag>> {
593 let this = self.eval_context_mut();
595 if let Some(old_alloc) = this.machine.threads.get_thread_local_alloc_id(def_id) {
596 // We already have a thread-specific allocation id for this
597 // thread-local static.
600 // We need to allocate a thread-specific allocation id for this
601 // thread-local static.
602 // First, we compute the initial value for this static.
603 if tcx.is_foreign_item(def_id) {
604 throw_unsup_format!("foreign thread-local statics are not supported");
606 let allocation = tcx.eval_static_initializer(def_id)?;
607 let mut allocation = allocation.inner().clone();
608 // This allocation will be deallocated when the thread dies, so it is not in read-only memory.
609 allocation.mutability = Mutability::Mut;
610 // Create a fresh allocation with this content.
611 let new_alloc = this.allocate_raw_ptr(allocation, MiriMemoryKind::Tls.into())?;
612 this.machine.threads.set_thread_local_alloc(def_id, new_alloc);
618 fn create_thread(&mut self) -> ThreadId {
619 let this = self.eval_context_mut();
620 let id = this.machine.threads.create_thread();
621 if let Some(data_race) = &mut this.machine.data_race {
622 data_race.thread_created(&this.machine.threads, id);
628 fn detach_thread(&mut self, thread_id: ThreadId) -> InterpResult<'tcx> {
629 let this = self.eval_context_mut();
630 this.machine.threads.detach_thread(thread_id)
634 fn join_thread(&mut self, joined_thread_id: ThreadId) -> InterpResult<'tcx> {
635 let this = self.eval_context_mut();
636 this.machine.threads.join_thread(joined_thread_id, this.machine.data_race.as_mut())?;
641 fn set_active_thread(&mut self, thread_id: ThreadId) -> ThreadId {
642 let this = self.eval_context_mut();
643 this.machine.threads.set_active_thread_id(thread_id)
647 fn get_active_thread(&self) -> ThreadId {
648 let this = self.eval_context_ref();
649 this.machine.threads.get_active_thread_id()
653 fn active_thread_mut(&mut self) -> &mut Thread<'mir, 'tcx> {
654 let this = self.eval_context_mut();
655 this.machine.threads.active_thread_mut()
659 fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
660 let this = self.eval_context_ref();
661 this.machine.threads.active_thread_ref()
665 fn get_total_thread_count(&self) -> usize {
666 let this = self.eval_context_ref();
667 this.machine.threads.get_total_thread_count()
671 fn has_terminated(&self, thread_id: ThreadId) -> bool {
672 let this = self.eval_context_ref();
673 this.machine.threads.has_terminated(thread_id)
677 fn have_all_terminated(&self) -> bool {
678 let this = self.eval_context_ref();
679 this.machine.threads.have_all_terminated()
683 fn enable_thread(&mut self, thread_id: ThreadId) {
684 let this = self.eval_context_mut();
685 this.machine.threads.enable_thread(thread_id);
689 fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
690 let this = self.eval_context_ref();
691 this.machine.threads.active_thread_stack()
695 fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
696 let this = self.eval_context_mut();
697 this.machine.threads.active_thread_stack_mut()
701 fn set_active_thread_name(&mut self, new_thread_name: Vec<u8>) {
702 let this = self.eval_context_mut();
703 this.machine.threads.set_active_thread_name(new_thread_name);
707 fn get_active_thread_name<'c>(&'c self) -> &'c [u8]
711 let this = self.eval_context_ref();
712 this.machine.threads.get_active_thread_name()
716 fn block_thread(&mut self, thread: ThreadId) {
717 let this = self.eval_context_mut();
718 this.machine.threads.block_thread(thread);
722 fn unblock_thread(&mut self, thread: ThreadId) {
723 let this = self.eval_context_mut();
724 this.machine.threads.unblock_thread(thread);
728 fn yield_active_thread(&mut self) {
729 let this = self.eval_context_mut();
730 this.machine.threads.yield_active_thread();
734 fn maybe_preempt_active_thread(&mut self) {
737 let this = self.eval_context_mut();
738 if this.machine.rng.get_mut().gen_bool(this.machine.preemption_rate) {
739 this.yield_active_thread();
744 fn register_timeout_callback(
748 callback: TimeoutCallback<'mir, 'tcx>,
750 let this = self.eval_context_mut();
751 this.machine.threads.register_timeout_callback(thread, call_time, callback);
755 fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
756 let this = self.eval_context_mut();
757 this.machine.threads.unregister_timeout_callback_if_exists(thread);
760 /// Execute a timeout callback on the callback's thread.
762 fn run_timeout_callback(&mut self) -> InterpResult<'tcx> {
763 let this = self.eval_context_mut();
764 let (thread, callback) =
765 if let Some((thread, callback)) = this.machine.threads.get_ready_callback() {
768 // get_ready_callback can return None if the computer's clock
769 // was shifted after calling the scheduler and before the call
770 // to get_ready_callback (see issue
771 // https://github.com/rust-lang/miri/issues/1763). In this case,
772 // just do nothing, which effectively just returns to the
776 // This back-and-forth with `set_active_thread` is here because of two
778 // 1. Make the caller and not the callback responsible for changing
780 // 2. Make the scheduler the only place that can change the active
782 let old_thread = this.set_active_thread(thread);
784 this.set_active_thread(old_thread);
788 /// Decide which action to take next and on which thread.
790 fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
791 let this = self.eval_context_mut();
792 this.machine.threads.schedule()
795 /// Handles thread termination of the active thread: wakes up threads joining on this one,
796 /// and deallocated thread-local statics.
798 /// This is called from `tls.rs` after handling the TLS dtors.
800 fn thread_terminated(&mut self) -> InterpResult<'tcx> {
801 let this = self.eval_context_mut();
802 for ptr in this.machine.threads.thread_terminated(this.machine.data_race.as_mut()) {
803 this.deallocate_ptr(ptr.into(), None, MiriMemoryKind::Tls.into())?;