Where
https://perldoc.perl.org/perlthrtut#A-Thread-Pitfall:-Deadlocks
Description
The following example code in the Perl Threads tutorial section "A Thread Pitfall: Deadlocks" does not work (v5.40.0 et al):
use threads;
my $x :shared = 4;
my $y :shared = 'foo';
my $thr1 = threads->create(sub {
lock($x);
sleep(20);
lock($y);
});
my $thr2 = threads->create(sub {
lock($y);
sleep(20);
lock($x);
});
=comment
Expected: Thread deadlock.
Actual: Script terminates with:
Perl exited with active threads:
2 running and unjoined
0 finished and unjoined
0 running and detached
and/or does not lock when threads are join()'d.
=cut
Suggested fix:
use threads;
use threads::shared;
my $x :shared = 4;
my $y :shared = 'foo';
my $thr1 = threads->create(sub {
lock($x);
sleep(20);
lock($y);
});
my $thr2 = threads->create(sub {
lock($y);
sleep(20);
lock($x);
});
$thr1->join();
$thr2->join();