开发者

What is the rule of thumb for incrementing reference counts?

When sending reference counted objects to other threads, is it better a better rule of thumb to increm开发者_运维技巧ent 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?


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... :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜