< 返回版块

laurencechan 发表于 2019-10-23 16:37

Tags:多线程

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

fn main() { let counter = Arc::new(Mutex::new(5)); let bor = Arc::clone(&counter); let handle2 = thread::spawn(move || { for _i in 0..10 { let mut num = bor.lock().unwrap(); println!("num is: {}", num); *num += 1; thread::sleep(Duration::from_secs(1)) }

});
thread::sleep(Duration::from_secs(3));
println!("counter has been changed to {:?} by the slave thread", counter.lock().unwrap());
println!("drop counter");
drop(counter);
handle2.join().unwrap();

}

输出: num is: 5 num is: 6 num is: 7 num is: 8 counter has been changed to 9 by the slave thread drop counter num is: 9 num is: 10 num is: 11 num is: 12 num is: 13 num is: 14

评论区

写评论
fakeshadow 2019-10-26 12:07

Arc是原子计数引用,只有当引用次数为0了才会被drop.如果你需要在某处强制drop,那么用downgrade把Weak传给其他线程是比较好的做法

Ryan-Git 2019-10-23 20:39

arc 是线程安全的引用计数,类似 shared_ptr.

c5soft 2019-10-23 20:20

最简便的方法:VSCode打开源代码,按Alt+Shift+F,前提是安装了Rust(rls)。 对以下内容的回复:

chirsz-ever 2019-10-23 17:05

对以下内容的回复:

这个论坛是支持 Markdown 语法的。代码格式要这么写:

    ```rust
    // code
    ```

重新排版了你的代码:

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

fn main() {
    let counter = Arc::new(Mutex::new(5));
    let bor = Arc::clone(&counter);
    let handle2 = thread::spawn(move || {
        for _i in 0..10 {
            let mut num = bor.lock().unwrap();
            println!("num is: {}", num);
            *num += 1;
            thread::sleep(Duration::from_secs(1))
        }
    });
    thread::sleep(Duration::from_secs(3));
    println!(
        "counter has been changed to {:?} by the slave thread",
        counter.lock().unwrap()
    );
    println!("drop counter");
    drop(counter);
    handle2.join().unwrap();
}

playground

这段代码中 counterArc 类型,也就是 Asynchronous Reference Count,异步(线程安全的)引用计数智能指针,是 Rc 的线程安全版本,主线程中的 drop 只是让 counter 的引用计数减 1,其内部的 Mutex 对象并不会被释放。

作者 laurencechan 2019-10-23 16:42

为什么只有中间一段代码有正常的格式

作者 laurencechan 2019-10-23 16:41

怎么调整代码格式啊?

1 共 6 条评论, 1 页