Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Arc example rarely executes all threads #1557

Closed
c-antin opened this issue Jun 20, 2022 · 5 comments
Closed

Arc example rarely executes all threads #1557

c-antin opened this issue Jun 20, 2022 · 5 comments

Comments

@c-antin
Copy link

c-antin commented Jun 20, 2022

Running the example of Arc results in a variing number of prints.

Is this a bug in rust or is thread::spawn not used correctly/up-to-date? Sometimes there are even incomplete prints:
image

@c-antin
Copy link
Author

c-antin commented Jun 20, 2022

Oh, I know the reason now! The main thread ends before all threads are run.
See https://doc.rust-lang.org/book/ch16-01-threads.html

@c-antin
Copy link
Author

c-antin commented Jun 20, 2022

This way all threads are waited for:

use std::sync::Arc;
use std::thread;

fn main() {
    // This variable declaration is where its value is specified.
    let apple = Arc::new("the same apple");

    let mut threads = vec![];

    for _ in 0..10 {
        // Here there is no value specification as it is a pointer to a reference
        // in the memory heap.
        let apple = Arc::clone(&apple);

        threads.push(thread::spawn(move || {
            // As Arc was used, threads can be spawned using the value allocated
            // in the Arc variable pointer's location.
            println!("{:?}", apple);
        }));
    }

    for handle in threads {
        handle.join().unwrap();
    }
}

@Rqnsom
Copy link
Contributor

Rqnsom commented Jun 27, 2022

Hi c-antin,

I've updated this just recently, but without using join function, but with sleep instead:

Joining threads could be used, but that concept is later introduced in 20.1. Threads, so I prefer simple sleep here.

See my PR for more:
#1552 (comment)

@Rqnsom
Copy link
Contributor

Rqnsom commented Jun 29, 2022

Should we then close this issue?

@marioidival
Copy link
Member

Yes! Thanks for that @Rqnsom and @c-antin

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants