【问题标题】:Multithreaded application fails to compile with error-chain多线程应用程序无法使用错误链编译
【发布时间】:2018-03-11 12:06:42
【问题描述】:

我将error-chain 引入到以前工作的应用程序中。错误本身很清楚,std::error::Error + 'static 缺少trait std::marker::Send 的实现:

error[E0277]: the trait bound `std::error::Error + 'static: std::marker::Send` is not satisfied
  --> src/main.rs:35:5
   |
35 | /     error_chain!{
36 | |
37 | |         foreign_links {
38 | |             Mqttc(::mqttc::Error);
...  |
53 | |         }
54 | |     }
   | |_____^ `std::error::Error + 'static` cannot be sent between threads safely
   |
   = help: the trait `std::marker::Send` is not implemented for `std::error::Error + 'static`
   = note: required because of the requirements on the impl of `std::marker::Send` for `std::ptr::Unique<std::error::Error + 'static>`
   = note: required because it appears within the type `std::boxed::Box<std::error::Error + 'static>`
   = note: required because it appears within the type `mqttc::netopt::Error`
   = note: required because it appears within the type `mqttc::Error`
   = note: required because it appears within the type `errors::ErrorKind`
   = note: required because it appears within the type `errors::Error`
   = note: required by `error_chain::ChainedError`
   = note: this error originates in a macro outside of the current crate

我不确定如何解决这个问题。请注意,我使用的是 more up to date fork of mqttc/mqtt3 而不是上游 crates。

【问题讨论】:

  • 你不能在线程之间共享任何对象。您必须使用互斥锁。
  • 所以本质上错误链声明了一些我想在多线程中使用的静态实体。如何使用错误链处理这个用例?
  • 我不知道这个箱子,但也许你应该在 github 问题中提问?
  • @Boiethios OP 不是试图在多个线程之间共享一个对象,而是(根据错误消息)在线程之间 send(移动)一个对象。 Send 几乎被 Rust 中的所有对象支持,除了少数特别列入黑名单的对象,例如 Rc

标签: multithreading rust


【解决方案1】:

mqttc::Error 包含 mqttc::netopt::Error,而 Box&lt;std::error::Error&gt; 又包含 std::boxed::Box&lt;std::error::Error + 'static&gt;std::error::Error 这里是一个 trait 对象。因为 Error trait 没有 Send作为一个超特征,Error 的实现不需要实现Send。因此,Box&lt;std::error::Error&gt; 不实现Send,因为并非所有类型T: std::error::Error 都实现Send

可以通过将 mqttc::netopt::Error 类型更改为使用 Box&lt;std::error::Error + Send&gt; 而不是 Box&lt;std::error::Error&gt; 来解决此问题(这将是库的重大更改)。

【讨论】:

  • 很好的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-15
  • 1970-01-01
  • 1970-01-01
  • 2018-08-15
  • 2020-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多