# Make a copy of a complex data structure that is thread-shared. # If not thread sharing, then make a 'regular' copy. sub shared_copy { my $in = $_[0]; # Make copies of array, hash and scalar refs if (my $ref_type = ref($in)) { # Copy an array ref if ($ref_type eq 'ARRAY') { # Make empty shared array ref my $out = ($threads::shared::threads_shared) ? &threads::shared::share([]) : []; # Recursively copy and add contents for my $val (@$in) { push(@$out, shared_copy($val)); } return ($out); } # Copy a hash ref if ($ref_type eq 'HASH') { # Make empty shared hash ref my $out = ($threads::shared::threads_shared) ? &threads::shared::share({}) : {}; # Recursively copy and add contents while (my ($key, $val) = each(%$in)) { $out->{$key} = shared_copy($val); } return ($out); } # Copy a scalar ref if ($ref_type eq 'SCALAR') { if ($threads::shared::threads_shared) { return (threads::shared::share($in)); } # If not sharing, then make a copy of the scalar ref my $out = \do{ my $scalar; }; $$out = $$in; return ($out); } } # Just return anything else # NOTE: This will generate an error if we're thread-sharing, # and $in is not an ordinary scalar. return ($in); }