增加引用计数的经验法则是什么?
将引用计数对象发送到其他线程时,根据经验,在启动线程之前或在线程内增加计数是否更好?
从更一般的意义上来说,我(作为一个函数)是否应该假设传递给我的参数已经被考虑在内?
When sending reference counted objects to other threads, is it better a better rule of thumb to increment the count before launching the thread or within the thread?
In a more general sense, should I (as a function) assume the parameters passed to me are already accounted for or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在将对象传递到的新线程中增加计数几乎肯定是错误的。 “父”线程中的任意数量的代码可能会在新的“子”线程开始运行之前运行,在这种情况下,“父”线程中的函数可能会返回,执行一些其他操作,将引用计数减少到 0 ,并释放该对象。然后,新线程将触及无效内存,调用未定义的行为,一切都会失败。
还请注意,此类错误可能会在很长一段时间内未被检测到,因为从统计角度来看,新线程不立即运行是不寻常的。事实上,最先发现该错误的可能是您的客户/客户...:-)
Incrementing the count within a new thread you pass the object to is almost certainly wrong. An arbitrary amount of code in the "parent" thread may run before the new "child" thread gets to run at all, in which case the function in the "parent" might return, do some other stuff, decrement the reference count to 0, and free the object. The new thread will then touch invalid memory, invoking undefined behavior, and all hell will break lose.
Further note that such bugs will probably go undetected for a long time, since it's statistically unusual for the new thread not to run immediately. In fact it will probably be your customers/clients who see the bug first... :-)