我可以安全地对不是多线程的对象进行多线程吗? [英] Can I safely multithread something which isn't meant to be multithreaded?

查看:88
本文介绍了我可以安全地对不是多线程的对象进行多线程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的特征不是围绕多线程(草书)设计的.

I'm using a trait which isn't designed around multithreading (Cursive).

现在,当它使用多线程时,它将位于互斥锁之后,因此它将无法同时在两个线程中使用.

Now, while it's using multithreading, it's going to be behind a mutex, so it won't be able to be used at two threads at the same time.

什么是铁锈试图保护我免受伤害,我能对此采取任何措施吗?

What is rust trying to protect me against and can I do anything about it?

作为示例参考,我的示例代码为:

For sample reference, my sample code is:

extern crate cursive;

use cursive::Cursive;
use std::thread;
use std::sync::{Mutex,Arc};

fn main() {
    let mut siv = Arc::new(Mutex::new(Cursive::default()));
    let copy_siv = siv.clone();

    thread::spawn(move || {
        let mut new_siv = copy_siv.lock().unwrap();
    });

    (*(siv.lock().unwrap())).run();
 }

编译器在thread::spawn处抱怨:

   Error[E0277]: `(dyn cursive::traits::View + 'static)` cannot be sent between threads safely
   --> src/main.rs:16:5
   |
16 |     thread::spawn(move || {
   |     ^^^^^^^^^^^^^ `(dyn cursive::traits::View + 'static)` cannot be sent between threads safely
   |
   = help: the trait `std::marker::Send` is not implemented for `(dyn cursive::traits::View + 'static)`

推荐答案

什么是铁锈试图保护我免受[...]

What is rust trying to protect me against [...]

在线程之间发送的内容中包含dyn cursive::traits::View特征对象.此特征对象不是Send.它必须为Send,因为通过将其放入Arc中,您将无法再预测哪个线程负责销毁它,因此必须安全地在线程之间转移所有权.

Something in what you're sending between threads contains a dyn cursive::traits::View trait object. This trait object is not Send. It needs to be Send because by putting it inside an Arc, you can no longer predict which thread will be responsible for destroying it, so it must be safe to transfer ownership between threads.

[...]我能做些什么吗?

[...] can I do anything about it?

您没有提供足够的背景信息来肯定地说,但可能没有.

You haven't provided enough context to say for certain, but probably not.

您可以也许尝试使用普通借用的引用(加上支持作用域线程的线程库),但我不能说这是否对您有用.

You could maybe try using a plain borrowed reference (plus a threading library that supports scoped threads), but I can't say if that will work for you.

为什么Mutex不能使其同步?这不是Mutex的重点吗?

Why wouldn't Mutex make it sync? Isn't that the point of Mutex?

不.当它还不是线程安全的时,它不能使某些事情成为线程安全的. Mutex仅管理对值的独占访问,并不能保证从不同线程进行的访问都是安全的.唯一可以使类型成为线程安全的是所讨论的类型.

No. It can't make something thread-safe when it wasn't already thread-safe. Mutex just manages exclusive access to a value, it doesn't make that access from different threads safe. The only thing that can make a type thread-safe is the type in question.

进行猜测:库的编写不需要任何线程安全性,因此Arc无法假定它是线程安全的,因此它拒绝编译.

Making a guess: the library was written such that it does not require thread safety, thus Arc cannot assume it's thread-safe, so it refuses to compile.

这篇关于我可以安全地对不是多线程的对象进行多线程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆