]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - t/41-clone.t
Fix leaks of cloned coderefs that access lexicals
[perl/modules/Variable-Magic.git] / t / 41-clone.t
1 #!perl -T
2
3 use strict;
4 use warnings;
5
6 use Config qw/%Config/;
7
8 BEGIN {
9  if (!$Config{useithreads}) {
10   require Test::More;
11   Test::More->import;
12   plan(skip_all => 'This perl wasn\'t built to support threads');
13  }
14 }
15
16 use threads; # Before Test::More
17 use threads::shared;
18
19 use Test::More;
20
21 use Variable::Magic qw/wizard cast dispell getdata getsig VMG_THREADSAFE/;
22
23 if (VMG_THREADSAFE) {
24  plan tests => 3 + 2 * (2 * 8 + 2) + 2 * (2 * 5 + 2);
25  my $v = $threads::VERSION;
26  diag "Using threads $v" if defined $v;
27  $v = $threads::shared::VERSION;
28  diag "Using threads::shared $v" if defined $v;
29 } else {
30  plan skip_all => 'This Variable::Magic isn\'t thread safe';
31 }
32
33 my $destroyed : shared = 0;
34 my $c         : shared = 0;
35 my $wiz = eval {
36  wizard get  => sub { ++$c },
37         data => sub { $_[1] + threads->tid() },
38         free => sub { ++$destroyed }
39 };
40 is($@,     '',    "wizard in main thread doesn't croak");
41 isnt($wiz, undef, "wizard in main thread is defined");
42 is($c,     0,     "wizard in main thread doesn't trigger magic");
43
44 my $sig;
45
46 sub try {
47  my ($dispell) = @_;
48  my $tid = threads->tid();
49  my $a   = 3;
50  my $res = eval { cast $a, $sig, sub { 5 }->() };
51  is($@, '', "cast in thread $tid doesn't croak");
52  my $b;
53  eval { $b = $a };
54  is($@, '', "get in thread $tid doesn't croak");
55  is($b, 3,  "get in thread $tid returns the right thing");
56  my $d = eval { getdata $a, $sig };
57  is($@, '',       "getdata in thread $tid doesn't croak");
58  is($d, 5 + $tid, "getdata in thread $tid returns the right thing");
59  if ($dispell) {
60   $res = eval { dispell $a, $sig };
61   is($@, '', "dispell in thread $tid doesn't croak");
62   undef $b;
63   eval { $b = $a };
64   is($@, '', "get in thread $tid after dispell doesn't croak");
65   is($b, 3,  "get in thread $tid after dispell returns the right thing");
66  }
67  return; # Ugly if not here
68 }
69
70 for my $dispell (1, 0) {
71  $c = 0;
72  $destroyed = 0;
73  $sig = $wiz;
74
75  my @t = map { threads->create(\&try, $dispell) } 1 .. 2;
76  $t[0]->join;
77  $t[1]->join;
78
79  is($c, 2, "get triggered twice");
80  is($destroyed, (1 - $dispell) * 2, 'destructors');
81
82  $c = 0;
83  $destroyed = 0;
84  $sig = getsig $wiz;
85
86  @t = map { threads->create(\&try, $dispell) } 1 .. 2;
87  $t[0]->join;
88  $t[1]->join;
89
90  is($c, 2, "get triggered twice");
91  is($destroyed, (1 - $dispell) * 2, 'destructors');
92 }