且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

线程引用需要静态生命周期?

更新时间:2023-01-25 17:29:38

在本质上,ArcMutex 包装是多余的:您传递的是对某物的引用在本地堆栈上.当您使用 std::thread::spawn 生成线程时,没有任何东西将生命周期链接在一起;主线程非常***地结束并释放其中的任何内容——在这种情况下,包括 a——在它产生的任何其他线程甚至开始执行之前;因此,在这种情况下,a 可以在生成的线程执行任何操作时引用已释放的内存,而将 c_clone 保留为悬空指针.这就是为什么一个衍生线程的关闭环境必须是'static.

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.