Monday, July 24, 2023

I am such a rust programmer.

 I tried to see how to use `static mut SOMEVAL` - turns out, I can do it by wrapping them in `unsafe`. I somehow feel guilty of doing this.



use std::thread;

static mut SOMEVAL: i32 = 10;
const THREAD_COUNT: usize = 100;

fn main() {
    let mut handles = vec![];
    for _i in 0..THREAD_COUNT {
        handles.push(thread::spawn(move || {
            unsafe {
                SOMEVAL += 1;
            }
            // panic!("hehe");
            1
        }));
    }

    for handle in handles {
        // ignoring return value with ok(), 
        // which might not always work nice.
        // See https://users.rust-lang.org/t/what-is-the-best-way-to-ignore-a-result/55187/6
        if handle.join().ok().unwrap() == 0 {
            println!("Well, that's awkward");
        }
    }

    unsafe {
        println!("sum total {}",SOMEVAL);
    }
}

1 comment: