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?
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... :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With