multithreading - 如何将对堆栈变量的引用传递给线程?

标签 multithreading rust reference lifetime

我正在编写一个 WebSocket 服务器,网络客户端连接到该服务器以与多线程计算机 AI 下棋。 WebSocket 服务器想要将 Logger 对象传递到 AI 代码中。 Logger 对象将通过管道将日志行从 AI 传输到 Web 客户端。 Logger 必须包含对客户端连接的引用。

我对生命周期如何与线程交互感到困惑。我用类型参数化的 Wrapper 结构重现了这个问题。 run_thread 函数尝试解包值并记录它。

use std::fmt::Debug;
use std::thread;

struct Wrapper<T: Debug> {
    val: T,
}

fn run_thread<T: Debug>(wrapper: Wrapper<T>) {
    let thr = thread::spawn(move || {
        println!("{:?}", wrapper.val);
    });

    thr.join();
}

fn main() {
    run_thread(Wrapper::<i32> { val: -1 });
}

wrapper 参数存在于堆栈中,它的生命周期不会超过 run_thread 的堆栈帧,即使线程将在堆栈帧之前加入结束。我可以从堆栈中复制值:

use std::fmt::Debug;
use std::thread;

struct Wrapper<T: Debug + Send> {
    val: T,
}

fn run_thread<T: Debug + Send + 'static>(wrapper: Wrapper<T>) {
    let thr = thread::spawn(move || {
        println!("{:?}", wrapper.val);
    });

    thr.join();
}

fn main() {
    run_thread(Wrapper::<i32> { val: -1 });
}

如果 T 是对我不想复制的大对象的引用,这将不起作用:

use std::fmt::Debug;
use std::thread;

struct Wrapper<T: Debug + Send> {
    val: T,
}

fn run_thread<T: Debug + Send + 'static>(wrapper: Wrapper<T>) {
    let thr = thread::spawn(move || {
        println!("{:?}", wrapper.val);
    });

    thr.join();
}

fn main() {
    let mut v = Vec::new();
    for i in 0..1000 {
        v.push(i);
    }

    run_thread(Wrapper { val: &v });
}

结果是:

error: `v` does not live long enough
  --> src/main.rs:22:32
   |
22 |     run_thread(Wrapper { val: &v });
   |                                ^ does not live long enough
23 | }
   | - borrowed value only lives until here
   |
   = note: borrowed value must be valid for the static lifetime...

我能想到的唯一解决方案是使用 Arc

use std::fmt::Debug;
use std::sync::Arc;
use std::thread;

struct Wrapper<T: Debug + Send + Sync + 'static> {
    arc_val: Arc<T>,
}

fn run_thread<T: Debug + Send + Sync + 'static>(wrapper: &Wrapper<T>) {
    let arc_val = wrapper.arc_val.clone();
    let thr = thread::spawn(move || {
        println!("{:?}", *arc_val);
    });

    thr.join();
}

fn main() {
    let mut v = Vec::new();
    for i in 0..1000 {
        v.push(i);
    }

    let w = Wrapper { arc_val: Arc::new(v) };
    run_thread(&w);

    println!("{}", (*w.arc_val)[0]);
}

在我的真实程序中,Logger 和连接对象似乎都必须放在 Arc 包装器中。当代码在库内部并行化时,客户端需要将连接装在 Arc 中似乎很烦人。这特别烦人,因为连接的生命周期保证大于工作线程的生命周期。

我错过了什么吗?

最佳答案

标准库中的基本线程支持允许创建的线程比创建它们的线程活得更久;这是好事!但是,如果您要将对堆栈分配变量的引用传递给这些线程之一,则无法保证该变量在线程执行时仍然有效。在其他语言中,这将允许线程访问无效内存,从而产生一堆内存安全问题。

一个解决方案是作用域线程——保证在父线程退出之前退出的线程。这些可以确保父线程中的堆栈变量在线程的整个持续时间内都可用。

使用rust 1.63

std::thread::scope时隔 7 年( removal , return )后返回稳定的 Rust。

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

fn main() {
    let mut vec = vec![1, 2, 3, 4, 5];

    thread::scope(|scope| {
        for e in &mut vec {
            scope.spawn(move || {
                thread::sleep(Duration::from_secs(1));
                *e += 1;
            });
        }
    });

    println!("{:?}", vec);
}

早期的 Rust 版本或当您需要更多控制时

横梁

我们不局限于标准库;一个流行的作用域线程 crate 是 crossbeam :

use crossbeam; // 0.6.0
use std::{thread, time::Duration};

fn main() {
    let mut vec = vec![1, 2, 3, 4, 5];

    crossbeam::scope(|scope| {
        for e in &mut vec {
            scope.spawn(move |_| {
                thread::sleep(Duration::from_secs(1));
                *e += 1;
            });
        }
    })
    .expect("A child thread panicked");

    println!("{:?}", vec);
}

人造丝

还有像rayon这样的 crate 抽象出“线程”的低级细节,但允许您实现您的目标:

use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator}; // 1.0.3
use std::{thread, time::Duration};

fn main() {
    let mut vec = vec![1, 2, 3, 4, 5];

    vec.par_iter_mut().for_each(|e| {
        thread::sleep(Duration::from_secs(1));
        *e += 1;
    });

    println!("{:?}", vec);
}

关于例子

每个示例都会生成多个线程,并在没有锁定、没有 Arc 和没有克隆的情况下就地改变一个本地向量。请注意,突变有一个 sleep 调用来帮助验证调用是否并行发生。

您可以扩展示例以共享对实现 Sync 的任何类型的引用,例如 MutexAtomic*。但是,使用这些会引入锁定。


the client is required to box the connection in an Arc when it is internal to the library that the code is parallelized

也许你可以更好地隐藏你的并行性?您能否接受记录器,然后将其包装在 Arc/Mutex 中,然后再将其交给您的线程?

关于multithreading - 如何将对堆栈变量的引用传递给线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32750829/

相关文章:

rust - 漂亮地打印带有分隔符的 Vec<char>

multithreading - 如何将 Tokio 线程池限制为一定数量的 native 线程?

mysql - SQL 错误 1452 : Cannot add or update child row

python - 如何通过引用传递变量?

java - 线程完成工作后如何返回值?

javascript - Web Worker 消耗大量内存

rust - 在 Rust 中合并两个 HashMap

java - Android Studio(引用对象)

java - 尝试实现工作线程

php - CURL 问题(多)