Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 236
Crazy Chenz Avatar asked May 11 '11 12:05

Crazy Chenz


1 Answers

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

like image 58
R.. GitHub STOP HELPING ICE Avatar answered Nov 08 '22 01:11

R.. GitHub STOP HELPING ICE