0

The extract below is from the rust documentation (https://doc.rust-lang.org/book/ch16-01-threads.html#creating-a-new-thread-with-spawn). Why does it say "allowing a different thread to run". Aren't threads running concurrently ,i.e at the same time?

From the docs:

The calls to thread::sleep force a thread to stop its execution for a short duration, allowing a different thread to run. The threads will probably take turns, but that isn’t guaranteed: it depends on how your operating system schedules the threads. In this run, the main thread printed first, even though the print statement from the spawned thread appears first in the code. And even though we told the spawned thread to print until i is 9, it only got to 5 before the main thread shut down.

If you run this code and only see output from the main thread, or don’t see any overlap, try increasing the numbers in the ranges to create more opportunities for the operating system to switch between the threads.

its an informational question

Ömer Erden
  • 7,680
  • 5
  • 36
  • 45
FreddyC
  • 11
  • 1
  • 3
  • Note that Rust uses native OS threads. As your docs quote says, "it depends on how your operating system schedules the threads". – justinas Oct 29 '22 at 20:02
  • Ok so i i understand correctly threads never execute in parallel no matter the OS on a single core machine, they just switch between each other. On multi core processor machine however threads actually can execute at the same time in parallel, thank @justinas – FreddyC Oct 29 '22 at 20:28

0 Answers0