Let me start by saying that this post is about fixing the bug in Net::SSH2
The issue I am facing is that Net::SSH2 wraps the objects in the underlaying libssh2 library using the sv_setref_pv function that just creates a new SV and places the pointer into the IV slot. When a thread containing Net::SSH2 objects creates a new thread, those SVs are cloned but the objects they point to are not. Later, when in some thread the object gets out of scope and its DESTROY method is called, the underlaying object is deallocated leaving the clones with a dangling pointer and after that, any use of those, including destroying then, may cause the application to crash.
So, my question is, what mechanism could be used to avoid that. How XS/C objects can be wrapped in a multi-thread friendly way?
The only viable way I can envision in to use magic for that, replacing the sv_setref_pv wrapping for one using a magic structure of type PERL_MAGIC_ext (~) with svt_dup pointing to a callback that does reference counting.
Are there any easier ways for doing it?