Reputation: 9158
I am new to Rust and trying to understand the Dining Philosopher code here :
https://google.github.io/comprehensive-rust/exercises/day-4/solutions-morning.html
By the time the execution reaches the following lines in the main thread, isn't it possible that none of the spawned threads have started executing their logic, resulting in nothing in 'rx' and the program simply quitting?
for thought in rx {
println!("{}", thought);
}
Upvotes: 1
Views: 80
Reputation: 3414
When iterating over a channel, it internally calls Receiver::recv, where the documentation specifies
This function will always block the current thread if there is no data available and it’s possible for more data to be sent (at least one sender still exists). Once a message is sent to the corresponding Sender (or SyncSender), this receiver will wake up and return that message.
So the receiver will block until it has data avalible, or all the senders have been dropped.
Upvotes: 3
Reputation: 59902
Yes, execution can reach for thought in rx { ... }
before the threads have even started. However, this will still work because iterating over a Receiver
will wait until there is a message and will only stop if all Sender
s have been destroyed (ergo it is no longer possible to receive any messages).
Upvotes: 2