Thread references require static lifetime?

后端 未结 1 1173
花落未央
花落未央 2020-11-29 13:20

While it makes sense intuitively that references passed to spawned threads need to have static lifetimes, I\'m unclear about what exactly is making the following code not co

相关标签:
1条回答
  • 2020-11-29 14:19

    In its essence, the Arc and Mutex wrapping is superfluous: you are passing a reference to something on the local stack. When you spawn a thread with std::thread::spawn, there is nothing linking the lifetimes together; the main thread is quite at liberty to conclude and free anything in it—in this case, including a—before any other threads it spawns even start executing; thus in this case a could refer to freed memory by the time the spawned thread does anything, leaving c_clone as a dangling pointer. This is why the environment of the closure of a spawned thread must be 'static.

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