Bpazy
Bpazy

Reputation: 192

std::sync::mpsc::channel always in the same order

No matter how many times I run the program, it always shows the numbers in the same order:

use std::sync::mpsc::channel;
use std::thread;

fn main() {
    let (tx, rx) = channel();
    for i in 0 ..10 {
        let tx = tx.clone();
        thread::spawn(move || {
            tx.send(i).unwrap();
        }); 
    }

    for _ in 0..10 {
        println!("{}", rx.recv().unwrap());
    }
}

Code on the playground. The output is:

6
7
8
5
9
4
3
2
1
0

If I rebuild the project, the sequence will change. Is the sequence decided at compile time?

Upvotes: 0

Views: 666

Answers (1)

Shepmaster
Shepmaster

Reputation: 431379

What order would you expect them to be in? For what it's worth, on my machine I ran the same binary twice and got slightly different results.

Ultimately, this comes down to how your operating system decides to schedule threads. You create 10 new threads and then ask the OS to run each of them when convenient. A hypothetical thread scheduler might look like this:

for thread in threads {
    if thread.runnable() {
        thread.run_for_a_time_slice();
    }
}

Where threads stores the threads in the order they were created. It's unlikely that any OS would be this naïve, but it shows the idea.

In your case, every thread is ready to run immediately, and is very short so it can run all the way to completion before the time is up.

Additionally, there might be some fairness being applied to the lock that guards the channel. Perhaps it always lets the first of multiple competing threads submit a value. Unfortunately, the implementation of channels is reasonably complex, so I can't immediately say if that's the case or not.

Upvotes: 4

Related Questions