Use shared_clone() to Share Variables among Perl Threads
Sharing variables across threads is generally very annoying in Perl. You have to declare the variable as shared before using it, and pay attention to the values you put in it.
Things get especially messy with multi-level hashes, since you are obligated to pre-declare each level as shared.
Luckily, there is a way to make things easier. If you upgrade threads::shared to version 1.32 using CPAN and can afford to waste some memory for a little, you can create your objects normally and then create shared copies of them using shared_clone().
This function will recursively traverse the object, create a shared clone of each element in it, and return you a nice reference which you can pass around to your threads.
At that point, to save memory, you can undef() the original object and keep only the clone.
This works great and flawlessly for read-only objects but it will still require some caution when you want to modify or add/append data to them since they need to be pre-declared as shared.
If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

