How do I share a generic struct between threads using Arc>>?

前端 未结 1 638
粉色の甜心
粉色の甜心 2020-12-11 22:04

I have some mutable state I need to share between threads. I followed the concurrency section of the Rust book, which shares a vector between threads and mutates it.

<
相关标签:
1条回答
  • 2020-12-11 22:22

    I'm trying to understand why M would need to implement Send, ...

    Because, as stated by the Send documentation:

    Types that can be transferred across thread boundaries.

    If it's not Send, it is by definition not safe to send to another thread.

    Almost all of the information you need is right there in the documentation:

    • thread::spawn requires the callable you give it to be Send.
    • You're using a closure, which is only Send if all the values it captures are Send. This is true in general of most types (they are Send if everything they're made of is Send, and similarly for Sync).
    • You're capturing data, which is an Arc<T>, which is only Send if T is Send.
    • T is a Mutex<U>, which is only Send if U is Send.
    • U is M. Thus, M must be Send.

    In addition, note that thread::spawn also requires that the callable be 'static, so you need that too. It needs that because if it didn't require that, it'd have no guarantee that the value will continue to exist for the entire lifetime of the thread (which may or may not outlive the thread that spawned it).

    ..., and what the appropriate way to accomplish this is.

    Same way as any other constraints: M: 'static + Send + Memory.

    0 讨论(0)
提交回复
热议问题