且构网

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

如何对线程使用静态生命周期?

更新时间:2023-01-25 17:16:32

&'a T 不能转换成 &'static T 除非泄漏记忆.幸运的是,这根本没有必要.没有理由向线程发送借用的指针并将行保留在主线程上.您不需要主线程上的行.只需发送行本身,即发送 String.

You can't convert &'a T into &'static T except by leaking memory. Luckily, this is not necessary at all. There is no reason to send borrowed pointers to the thread and keep the lines on the main thread. You don't need the lines on the main thread. Just send the lines themselves, i.e. send String.

如果需要从多个线程访问(并且您不想克隆),请使用Arc(将来,Arc 也可以工作).这样,字符串在线程之间共享,正确共享,以便在没有线程再使用它时准确地释放它.

If access from multiple threads was necessary (and you don't want to clone), use Arc<String> (in the future, Arc<str> may also work). This way the string is shared between threads, properly shared, so that it will be deallocated exactly when no thread uses it any more.

在线程之间发送非'static引用是不安全的,因为你永远不知道另一个线程会继续使用它多久,所以你不知道借用何时到期并且对象可以被释放.请注意,作用域线程没有这个问题(不在 1.0 中,但正如我们所说的那样正在重新设计)确实允许这样做,但是常规的、spawned 线程有.

Sending non-'static references between threads is unsafe because you never know how long the other thread will keep using it, so you don't know when the borrow expires and the object can be freed. Note that scoped threads don't have this problem (which aren't in 1.0 but are being redesigned as we speak) do allow this, but regular, spawned threads do.

'static 不是你应该避免的东西,它的作用非常好:表示一个值在程序运行的整个持续时间内都存在.但如果这不是您想要传达的内容,那当然是错误的工具.

'static is not something you should avoid, it is perfectly fine for what it does: Denoting that a value lives for the entire duration the program is running. But if that is not what you're trying to convey, of course it is the wrong tool.