【问题标题】:SDL2, FnMut and mpsc, sender can not be shared safely between threadsSDL2、FnMut 和 mpsc、sender 不能在线程之间安全共享
【发布时间】:2017-08-27 08:39:36
【问题描述】:

我想用sdl2-rs crate 启动一个计时器来执行绘图调用。我想通过这样做来开始它:

extern crate sdl2;

use std::sync::mpsc;

enum Event {
    Draw,
}

fn main() {
    let sdl_context = sdl2::init().unwrap();
    let video_subsystem = sdl_context.video().unwrap();
    video_subsystem.gl_attr().set_context_version(4, 5);
    println!(
        "Current gl version: {:?}",
        video_subsystem.gl_attr().context_version()
    );
    let timer_subsystem = sdl_context.timer().unwrap();

    let window = video_subsystem
        .window("rust-sdl2 demo: Video", 800, 600)
        .position_centered()
        .opengl()
        .build()
        .unwrap();

    let context = window.gl_create_context().unwrap();

    let (tx, rx) = mpsc::channel();
    {
        let timer_tx = tx.clone();
        timer_subsystem.add_timer(
            1000u32 / 120u32,
            Box::new(move || {
                timer_tx.send(Event::Draw);
                1000u32 / 120u32
            }),
        );
    }
}

但是,我收到此错误:

error[E0277]: the trait bound `std::sync::mpsc::Sender<Event>: std::marker::Sync` is not satisfied in `[closure@src/main.rs:33:22: 36:14 timer_tx:std::sync::mpsc::Sender<Event>]`
  --> src/main.rs:33:13
   |
33 | /             Box::new(move || {
34 | |                 timer_tx.send(Event::Draw);
35 | |                 1000u32 / 120u32
36 | |             }),
   | |______________^ `std::sync::mpsc::Sender<Event>` cannot be shared between threads safely
   |
   = help: within `[closure@src/main.rs:33:22: 36:14 timer_tx:std::sync::mpsc::Sender<Event>]`, the trait `std::marker::Sync` is not implemented for `std::sync::mpsc::Sender<Event>`
   = note: required because it appears within the type `[closure@src/main.rs:33:22: 36:14 timer_tx:std::sync::mpsc::Sender<Event>]`
   = note: required for the cast to the object type `std::ops::FnMut() -> u32 + std::marker::Sync`

我知道发件人不是Sync,所以我克隆它并将克隆的对象移动到FnMut 闭包中,但它无论如何都不起作用。我怎样才能做到这一点?据我了解,通过将对象移动到闭包中,我们共享它,因此它必须以这种方式工作。此外,文档中的示例也是如此。

【问题讨论】:

    标签: multithreading rust sdl-2


    【解决方案1】:

    克隆的发件人与原始发件人类型相同,因此仍然不是Syncadd_timer 函数需要一个 Sync 闭包,因此您需要将 sender 包装在 Mutex 中,这样您的发送者可以安全地在线程之间共享。

    let timer_tx = Mutex::new(tx.clone());
    timer_subsystem.add_timer(
        1000u32 / 120u32,
        Box::new(move || {
            timer_tx.lock().unwrap().send(Event::Draw);
            1000u32 / 120u32
        }),
    );
    

    【讨论】:

    • 这是正确的,但是,在克隆的情况下我不需要同步 - 我使用单独的对象,我认为我没有什么可分享的。还是我错了?
    • 需要Sync的是函数add_timer,而不是你。您必须遵守要求。
    猜你喜欢
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多