eyepopslikeamosquito has asked for the wisdom of the Perl Monks concerning the following question:

After getting the dreaded "Free to wrong pool" crash in a multi-threaded Perl program (in, I wrote this little program to demonstrate it:

#!/usr/bin/perl -w # Simulate "Free to wrong pool" crash from, line 1987 # This program crashes with Perl 5.8.4/5.8.5 (on multi-cpu boxes only) +. use strict; use threads; sub do_one_thread { my $kid = shift; warn "kid $kid before local\n"; for my $j (1..99999) { my @warns; { local $^W = 1; local $SIG{"__WARN__"} = sub { push @warns, @_ }; } } warn "kid $kid after local, sleeping 1\n"; sleep(1); warn "kid $kid exit\n"; } sub do_threads { my $nthreads = shift; my @kids = (); for my $i (0..$nthreads-1) { my $t = threads->new(\&do_one_thread, $i); warn "parent $$: continue\n"; push(@kids, $t); } for my $t (@kids) { warn "parent $$: waiting for join\n"; $t->join(); warn "parent $$: thread exited\n"; } } do_threads(2);

This crash seems related to Perl bug #31851 ("Threading crash with closures"). It seems Perl closures are not currently thread-safe. Though all the CVs are cloned for each thread, they share the same OP tree, and the code that updates the reference count of the OP tree is not thread safe because it's missing locks (OP_REFCNT_LOCK/OP_REFCNT_UNLOCK) around some refcount decrementing (OpREFCNT_dec) and some refcount incrementing (OpREFCNT_inc).

Alas, the fix for #31851 has not yet made it back into Perl 5.8.x branch. Moreover, I'd like to have this program not crash when running on earlier Perl versions. Accordingly, I'd like to find a way to replace closures with something else that is thread-safe.

I am currently changing, for example:

local $SIG{"__WARN__"} = sub { push @warns, @_ };


local $SIG{"__WARN__"} = eval <<'CLOSURE_HACK'; sub { push @warns, @_ } CLOSURE_HACK

which seems to get rid of the crashes. Given I don't understand the code I am changing very well, can you see cases where routinely adding a leading eval like this will cause trouble? Is there an alternative way to replace closures with something else?