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

Threads2 wrong solution possible #2200

Open
TheBlackArroVV opened this issue Jan 19, 2025 · 0 comments
Open

Threads2 wrong solution possible #2200

TheBlackArroVV opened this issue Jan 19, 2025 · 0 comments

Comments

@TheBlackArroVV
Copy link

TheBlackArroVV commented Jan 19, 2025

It is possible to pass threads2 without actually solving a task. Following code will make it great and allow to pass while being wrong. Maybe worth discarding as you can still get it by matching with expected result(10) and checking solution file

use std::{sync::Arc, thread, time::Duration};

#[derive(Clone)]
struct JobStatus {
    jobs_done: u32,
}

fn main() {
    // TODO: `Arc` isn't enough if you want a **mutable** shared state.
    let status = Arc::new(JobStatus { jobs_done: 0 });

    let mut handles = Vec::new();
    for _ in 0..10 {
        let mut status_shared = Arc::clone(&status);
        let handle = thread::spawn(move || {
            thread::sleep(Duration::from_millis(250));

            // TODO: You must take an action before you update a shared value.
            Arc::make_mut(&mut status_shared).jobs_done += 1;
        });
        handles.push(handle);
    }

    // Waiting for all jobs to complete.
    for handle in handles {
        handle.join().unwrap();
    }

    // TODO: Print the value of `JobStatus.jobs_done`.
    println!("Jobs done: {}", status.jobs_done);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant