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 /// A specific moment in time.
177 RealTime(SystemTime),
181 /// How long do we have to wait from now until the specified time?
182 fn get_wait_time(&self) -> Duration {
184 Time::Monotonic(instant) => instant.saturating_duration_since(Instant::now()),
185 Time::RealTime(time) =>
186 time.duration_since(SystemTime::now()).unwrap_or(Duration::new(0, 0)),
191 /// Callbacks are used to implement timeouts. For example, waiting on a
192 /// conditional variable with a timeout creates a callback that is called after
193 /// the specified time and unblocks the thread. If another thread signals on the
194 /// conditional variable, the signal handler deletes the callback.
195 struct TimeoutCallbackInfo<'mir, 'tcx> {
196 /// The callback should be called no earlier than this time.
198 /// The called function.
199 callback: TimeoutCallback<'mir, 'tcx>,
202 impl<'mir, 'tcx> std::fmt::Debug for TimeoutCallbackInfo<'mir, 'tcx> {
203 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
204 write!(f, "TimeoutCallback({:?})", self.call_time)
208 /// A set of threads.
210 pub struct ThreadManager<'mir, 'tcx> {
211 /// Identifier of the currently active thread.
212 active_thread: ThreadId,
213 /// Threads used in the program.
215 /// Note that this vector also contains terminated threads.
216 threads: IndexVec<ThreadId, Thread<'mir, 'tcx>>,
217 /// This field is pub(crate) because the synchronization primitives
218 /// (`crate::sync`) need a way to access it.
219 pub(crate) sync: SynchronizationState,
220 /// A mapping from a thread-local static to an allocation id of a thread
221 /// specific allocation.
222 thread_local_alloc_ids: RefCell<FxHashMap<(DefId, ThreadId), Pointer<Tag>>>,
223 /// A flag that indicates that we should change the active thread.
224 yield_active_thread: bool,
225 /// Callbacks that are called once the specified time passes.
226 timeout_callbacks: FxHashMap<ThreadId, TimeoutCallbackInfo<'mir, 'tcx>>,
229 impl<'mir, 'tcx> Default for ThreadManager<'mir, 'tcx> {
230 fn default() -> Self {
231 let mut threads = IndexVec::new();
232 // Create the main thread and add it to the list of threads.
233 let mut main_thread = Thread::default();
234 // The main thread can *not* be joined on.
235 main_thread.join_status = ThreadJoinStatus::Detached;
236 threads.push(main_thread);
238 active_thread: ThreadId::new(0),
240 sync: SynchronizationState::default(),
241 thread_local_alloc_ids: Default::default(),
242 yield_active_thread: false,
243 timeout_callbacks: FxHashMap::default(),
248 impl<'mir, 'tcx: 'mir> ThreadManager<'mir, 'tcx> {
249 /// Check if we have an allocation for the given thread local static for the
251 fn get_thread_local_alloc_id(&self, def_id: DefId) -> Option<Pointer<Tag>> {
252 self.thread_local_alloc_ids.borrow().get(&(def_id, self.active_thread)).cloned()
255 /// Set the pointer for the allocation of the given thread local
256 /// static for the active thread.
258 /// Panics if a thread local is initialized twice for the same thread.
259 fn set_thread_local_alloc(&self, def_id: DefId, ptr: Pointer<Tag>) {
260 self.thread_local_alloc_ids
262 .try_insert((def_id, self.active_thread), ptr)
266 /// Borrow the stack of the active thread.
267 pub fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
268 &self.threads[self.active_thread].stack
271 /// Mutably borrow the stack of the active thread.
272 fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
273 &mut self.threads[self.active_thread].stack
276 /// Create a new thread and returns its id.
277 fn create_thread(&mut self) -> ThreadId {
278 let new_thread_id = ThreadId::new(self.threads.len());
279 self.threads.push(Default::default());
283 /// Set an active thread and return the id of the thread that was active before.
284 fn set_active_thread_id(&mut self, id: ThreadId) -> ThreadId {
285 let active_thread_id = self.active_thread;
286 self.active_thread = id;
287 assert!(self.active_thread.index() < self.threads.len());
291 /// Get the id of the currently active thread.
292 fn get_active_thread_id(&self) -> ThreadId {
296 /// Get the total number of threads that were ever spawn by this program.
297 fn get_total_thread_count(&self) -> usize {
301 /// Has the given thread terminated?
302 fn has_terminated(&self, thread_id: ThreadId) -> bool {
303 self.threads[thread_id].state == ThreadState::Terminated
306 /// Have all threads terminated?
307 fn have_all_terminated(&self) -> bool {
308 self.threads.iter().all(|thread| thread.state == ThreadState::Terminated)
311 /// Enable the thread for execution. The thread must be terminated.
312 fn enable_thread(&mut self, thread_id: ThreadId) {
313 assert!(self.has_terminated(thread_id));
314 self.threads[thread_id].state = ThreadState::Enabled;
317 /// Get a mutable borrow of the currently active thread.
318 fn active_thread_mut(&mut self) -> &mut Thread<'mir, 'tcx> {
319 &mut self.threads[self.active_thread]
322 /// Get a shared borrow of the currently active thread.
323 fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
324 &self.threads[self.active_thread]
327 /// Mark the thread as detached, which means that no other thread will try
328 /// to join it and the thread is responsible for cleaning up.
329 fn detach_thread(&mut self, id: ThreadId) -> InterpResult<'tcx> {
330 if self.threads[id].join_status != ThreadJoinStatus::Joinable {
331 throw_ub_format!("trying to detach thread that was already detached or joined");
333 self.threads[id].join_status = ThreadJoinStatus::Detached;
337 /// Mark that the active thread tries to join the thread with `joined_thread_id`.
340 joined_thread_id: ThreadId,
341 data_race: Option<&mut data_race::GlobalState>,
342 ) -> InterpResult<'tcx> {
343 if self.threads[joined_thread_id].join_status != ThreadJoinStatus::Joinable {
344 throw_ub_format!("trying to join a detached or already joined thread");
346 if joined_thread_id == self.active_thread {
347 throw_ub_format!("trying to join itself");
352 .all(|thread| thread.state != ThreadState::BlockedOnJoin(joined_thread_id)),
353 "a joinable thread already has threads waiting for its termination"
355 // Mark the joined thread as being joined so that we detect if other
356 // threads try to join it.
357 self.threads[joined_thread_id].join_status = ThreadJoinStatus::Joined;
358 if self.threads[joined_thread_id].state != ThreadState::Terminated {
359 // The joined thread is still running, we need to wait for it.
360 self.active_thread_mut().state = ThreadState::BlockedOnJoin(joined_thread_id);
362 "{:?} blocked on {:?} when trying to join",
367 // The thread has already terminated - mark join happens-before
368 if let Some(data_race) = data_race {
369 data_race.thread_joined(self.active_thread, joined_thread_id);
375 /// Set the name of the active thread.
376 fn set_thread_name(&mut self, new_thread_name: Vec<u8>) {
377 self.active_thread_mut().thread_name = Some(new_thread_name);
380 /// Get the name of the active thread.
381 fn get_thread_name(&self) -> &[u8] {
382 self.active_thread_ref().thread_name()
385 /// Put the thread into the blocked state.
386 fn block_thread(&mut self, thread: ThreadId) {
387 let state = &mut self.threads[thread].state;
388 assert_eq!(*state, ThreadState::Enabled);
389 *state = ThreadState::BlockedOnSync;
392 /// Put the blocked thread into the enabled state.
393 fn unblock_thread(&mut self, thread: ThreadId) {
394 let state = &mut self.threads[thread].state;
395 assert_eq!(*state, ThreadState::BlockedOnSync);
396 *state = ThreadState::Enabled;
399 /// Change the active thread to some enabled thread.
400 fn yield_active_thread(&mut self) {
401 // We do not yield immediately, as swapping out the current stack while executing a MIR statement
402 // could lead to all sorts of confusion.
403 // We should only switch stacks between steps.
404 self.yield_active_thread = true;
407 /// Register the given `callback` to be called once the `call_time` passes.
409 /// The callback will be called with `thread` being the active thread, and
410 /// the callback may not change the active thread.
411 fn register_timeout_callback(
415 callback: TimeoutCallback<'mir, 'tcx>,
417 self.timeout_callbacks
418 .try_insert(thread, TimeoutCallbackInfo { call_time, callback })
422 /// Unregister the callback for the `thread`.
423 fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
424 self.timeout_callbacks.remove(&thread);
427 /// Get a callback that is ready to be called.
428 fn get_ready_callback(&mut self) -> Option<(ThreadId, TimeoutCallback<'mir, 'tcx>)> {
429 // We iterate over all threads in the order of their indices because
430 // this allows us to have a deterministic scheduler.
431 for thread in self.threads.indices() {
432 match self.timeout_callbacks.entry(thread) {
433 Entry::Occupied(entry) =>
434 if entry.get().call_time.get_wait_time() == Duration::new(0, 0) {
435 return Some((thread, entry.remove().callback));
437 Entry::Vacant(_) => {}
443 /// Wakes up threads joining on the active one and deallocates thread-local statics.
444 /// The `AllocId` that can now be freed are returned.
445 fn thread_terminated(
447 mut data_race: Option<&mut data_race::GlobalState>,
448 ) -> Vec<Pointer<Tag>> {
449 let mut free_tls_statics = Vec::new();
451 let mut thread_local_statics = self.thread_local_alloc_ids.borrow_mut();
452 thread_local_statics.retain(|&(_def_id, thread), &mut alloc_id| {
453 if thread != self.active_thread {
454 // Keep this static around.
457 // Delete this static from the map and from memory.
458 // We cannot free directly here as we cannot use `?` in this context.
459 free_tls_statics.push(alloc_id);
463 // Set the thread into a terminated state in the data-race detector
464 if let Some(ref mut data_race) = data_race {
465 data_race.thread_terminated();
467 // Check if we need to unblock any threads.
468 for (i, thread) in self.threads.iter_enumerated_mut() {
469 if thread.state == ThreadState::BlockedOnJoin(self.active_thread) {
470 // The thread has terminated, mark happens-before edge to joining thread
471 if let Some(ref mut data_race) = data_race {
472 data_race.thread_joined(i, self.active_thread);
474 trace!("unblocking {:?} because {:?} terminated", i, self.active_thread);
475 thread.state = ThreadState::Enabled;
481 /// Decide which action to take next and on which thread.
483 /// The currently implemented scheduling policy is the one that is commonly
484 /// used in stateless model checkers such as Loom: run the active thread as
485 /// long as we can and switch only when we have to (the active thread was
486 /// blocked, terminated, or has explicitly asked to be preempted).
489 data_race: &Option<data_race::GlobalState>,
490 ) -> InterpResult<'tcx, SchedulingAction> {
491 // Check whether the thread has **just** terminated (`check_terminated`
492 // checks whether the thread has popped all its stack and if yes, sets
493 // the thread state to terminated).
494 if self.threads[self.active_thread].check_terminated() {
495 return Ok(SchedulingAction::ExecuteDtors);
497 // If we get here again and the thread is *still* terminated, there are no more dtors to run.
498 if self.threads[MAIN_THREAD].state == ThreadState::Terminated {
499 // The main thread terminated; stop the program.
500 // We do *not* run TLS dtors of remaining threads, which seems to match rustc behavior.
501 return Ok(SchedulingAction::Stop);
503 // This thread and the program can keep going.
504 if self.threads[self.active_thread].state == ThreadState::Enabled
505 && !self.yield_active_thread
507 // The currently active thread is still enabled, just continue with it.
508 return Ok(SchedulingAction::ExecuteStep);
510 // The active thread yielded. Let's see if there are any timeouts to take care of. We do
511 // this *before* running any other thread, to ensure that timeouts "in the past" fire before
512 // any other thread can take an action. This ensures that for `pthread_cond_timedwait`, "an
513 // error is returned if [...] the absolute time specified by abstime has already been passed
514 // at the time of the call".
515 // <https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html>
516 let potential_sleep_time =
517 self.timeout_callbacks.values().map(|info| info.call_time.get_wait_time()).min();
518 if potential_sleep_time == Some(Duration::new(0, 0)) {
519 return Ok(SchedulingAction::ExecuteTimeoutCallback);
521 // No callbacks scheduled, pick a regular thread to execute.
522 // The active thread blocked or yielded. So we go search for another enabled thread.
523 // Curcially, we start searching at the current active thread ID, rather than at 0, since we
524 // want to avoid always scheduling threads 0 and 1 without ever making progress in thread 2.
526 // `skip(N)` means we start iterating at thread N, so we skip 1 more to start just *after*
527 // the active thread. Then after that we look at `take(N)`, i.e., the threads *before* the
532 .skip(self.active_thread.index() + 1)
533 .chain(self.threads.iter_enumerated().take(self.active_thread.index()));
534 for (id, thread) in threads {
535 debug_assert_ne!(self.active_thread, id);
536 if thread.state == ThreadState::Enabled {
537 self.active_thread = id;
538 if let Some(data_race) = data_race {
539 data_race.thread_set_active(self.active_thread);
544 self.yield_active_thread = false;
545 if self.threads[self.active_thread].state == ThreadState::Enabled {
546 return Ok(SchedulingAction::ExecuteStep);
548 // We have not found a thread to execute.
549 if self.threads.iter().all(|thread| thread.state == ThreadState::Terminated) {
550 unreachable!("all threads terminated without the main thread terminating?!");
551 } else if let Some(sleep_time) = potential_sleep_time {
552 // All threads are currently blocked, but we have unexecuted
553 // timeout_callbacks, which may unblock some of the threads. Hence,
554 // sleep until the first callback.
555 std::thread::sleep(sleep_time);
556 Ok(SchedulingAction::ExecuteTimeoutCallback)
558 throw_machine_stop!(TerminationInfo::Deadlock);
563 // Public interface to thread management.
564 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
565 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
566 /// Get a thread-specific allocation id for the given thread-local static.
567 /// If needed, allocate a new one.
568 fn get_or_create_thread_local_alloc(
571 ) -> InterpResult<'tcx, Pointer<Tag>> {
572 let this = self.eval_context_mut();
574 if let Some(old_alloc) = this.machine.threads.get_thread_local_alloc_id(def_id) {
575 // We already have a thread-specific allocation id for this
576 // thread-local static.
579 // We need to allocate a thread-specific allocation id for this
580 // thread-local static.
581 // First, we compute the initial value for this static.
582 if tcx.is_foreign_item(def_id) {
583 throw_unsup_format!("foreign thread-local statics are not supported");
585 let allocation = tcx.eval_static_initializer(def_id)?;
586 let mut allocation = allocation.inner().clone();
587 // This allocation will be deallocated when the thread dies, so it is not in read-only memory.
588 allocation.mutability = Mutability::Mut;
589 // Create a fresh allocation with this content.
590 let new_alloc = this.allocate_raw_ptr(allocation, MiriMemoryKind::Tls.into());
591 this.machine.threads.set_thread_local_alloc(def_id, new_alloc);
597 fn create_thread(&mut self) -> ThreadId {
598 let this = self.eval_context_mut();
599 let id = this.machine.threads.create_thread();
600 if let Some(data_race) = &mut this.machine.data_race {
601 data_race.thread_created(id);
607 fn detach_thread(&mut self, thread_id: ThreadId) -> InterpResult<'tcx> {
608 let this = self.eval_context_mut();
609 this.machine.threads.detach_thread(thread_id)
613 fn join_thread(&mut self, joined_thread_id: ThreadId) -> InterpResult<'tcx> {
614 let this = self.eval_context_mut();
615 this.machine.threads.join_thread(joined_thread_id, this.machine.data_race.as_mut())?;
620 fn set_active_thread(&mut self, thread_id: ThreadId) -> ThreadId {
621 let this = self.eval_context_mut();
622 if let Some(data_race) = &this.machine.data_race {
623 data_race.thread_set_active(thread_id);
625 this.machine.threads.set_active_thread_id(thread_id)
629 fn get_active_thread(&self) -> ThreadId {
630 let this = self.eval_context_ref();
631 this.machine.threads.get_active_thread_id()
635 fn active_thread_mut(&mut self) -> &mut Thread<'mir, 'tcx> {
636 let this = self.eval_context_mut();
637 this.machine.threads.active_thread_mut()
641 fn active_thread_ref(&self) -> &Thread<'mir, 'tcx> {
642 let this = self.eval_context_ref();
643 this.machine.threads.active_thread_ref()
647 fn get_total_thread_count(&self) -> usize {
648 let this = self.eval_context_ref();
649 this.machine.threads.get_total_thread_count()
653 fn has_terminated(&self, thread_id: ThreadId) -> bool {
654 let this = self.eval_context_ref();
655 this.machine.threads.has_terminated(thread_id)
659 fn have_all_terminated(&self) -> bool {
660 let this = self.eval_context_ref();
661 this.machine.threads.have_all_terminated()
665 fn enable_thread(&mut self, thread_id: ThreadId) {
666 let this = self.eval_context_mut();
667 this.machine.threads.enable_thread(thread_id);
671 fn active_thread_stack(&self) -> &[Frame<'mir, 'tcx, Tag, FrameData<'tcx>>] {
672 let this = self.eval_context_ref();
673 this.machine.threads.active_thread_stack()
677 fn active_thread_stack_mut(&mut self) -> &mut Vec<Frame<'mir, 'tcx, Tag, FrameData<'tcx>>> {
678 let this = self.eval_context_mut();
679 this.machine.threads.active_thread_stack_mut()
683 fn set_active_thread_name(&mut self, new_thread_name: Vec<u8>) {
684 let this = self.eval_context_mut();
685 if let Some(data_race) = &mut this.machine.data_race {
686 if let Ok(string) = String::from_utf8(new_thread_name.clone()) {
687 data_race.thread_set_name(this.machine.threads.active_thread, string);
690 this.machine.threads.set_thread_name(new_thread_name);
694 fn get_active_thread_name<'c>(&'c self) -> &'c [u8]
698 let this = self.eval_context_ref();
699 this.machine.threads.get_thread_name()
703 fn block_thread(&mut self, thread: ThreadId) {
704 let this = self.eval_context_mut();
705 this.machine.threads.block_thread(thread);
709 fn unblock_thread(&mut self, thread: ThreadId) {
710 let this = self.eval_context_mut();
711 this.machine.threads.unblock_thread(thread);
715 fn yield_active_thread(&mut self) {
716 let this = self.eval_context_mut();
717 this.machine.threads.yield_active_thread();
721 fn register_timeout_callback(
725 callback: TimeoutCallback<'mir, 'tcx>,
727 let this = self.eval_context_mut();
728 this.machine.threads.register_timeout_callback(thread, call_time, callback);
732 fn unregister_timeout_callback_if_exists(&mut self, thread: ThreadId) {
733 let this = self.eval_context_mut();
734 this.machine.threads.unregister_timeout_callback_if_exists(thread);
737 /// Execute a timeout callback on the callback's thread.
739 fn run_timeout_callback(&mut self) -> InterpResult<'tcx> {
740 let this = self.eval_context_mut();
741 let (thread, callback) =
742 if let Some((thread, callback)) = this.machine.threads.get_ready_callback() {
745 // get_ready_callback can return None if the computer's clock
746 // was shifted after calling the scheduler and before the call
747 // to get_ready_callback (see issue
748 // https://github.com/rust-lang/miri/issues/1763). In this case,
749 // just do nothing, which effectively just returns to the
753 // This back-and-forth with `set_active_thread` is here because of two
755 // 1. Make the caller and not the callback responsible for changing
757 // 2. Make the scheduler the only place that can change the active
759 let old_thread = this.set_active_thread(thread);
761 this.set_active_thread(old_thread);
765 /// Decide which action to take next and on which thread.
767 fn schedule(&mut self) -> InterpResult<'tcx, SchedulingAction> {
768 let this = self.eval_context_mut();
769 let data_race = &this.machine.data_race;
770 this.machine.threads.schedule(data_race)
773 /// Handles thread termination of the active thread: wakes up threads joining on this one,
774 /// and deallocated thread-local statics.
776 /// This is called from `tls.rs` after handling the TLS dtors.
778 fn thread_terminated(&mut self) -> InterpResult<'tcx> {
779 let this = self.eval_context_mut();
780 for ptr in this.machine.threads.thread_terminated(this.machine.data_race.as_mut()) {
781 this.deallocate_ptr(ptr.into(), None, MiriMemoryKind::Tls.into())?;