]> git.vpit.fr Git - perl/modules/Variable-Magic.git/blob - t/40-threads.t
Test destructors
[perl/modules/Variable-Magic.git] / t / 40-threads.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 VMG_THREADSAFE/;
22
23 if (VMG_THREADSAFE) {
24  plan tests => 2 * (2 * 16 + 1) + 2 * (2 * 11 + 1);
25 } else {
26  plan skip_all => 'This Variable::Magic isn\'t thread safe';
27 }
28
29 my $destroyed : shared = 0;
30 my $sig = undef;
31
32 sub try {
33  my ($dispell) = @_;
34  my $tid = threads->tid();
35  my $c   = 0;
36  my $wiz = eval {
37   wizard get  => sub { ++$c },
38          data => sub { $_[1] + $tid },
39          free => sub { ++$destroyed },
40          sig  => $sig;
41  };
42  is($@,     '',    "wizard in thread $tid doesn't croak");
43  isnt($wiz, undef, "wizard in thread $tid is defined");
44  is($c,     0,     "wizard in thread $tid doesn't trigger magic");
45  my $a = 3;
46  my $res = eval { cast $a, $wiz, sub { 5 }->() };
47  is($@, '', "cast in thread $tid doesn't croak");
48  is($c, 0,  "cast in thread $tid doesn't trigger magic");
49  my $b;
50  eval { $b = $a };
51  is($@, '', "get in thread $tid doesn't croak");
52  is($b, 3,  "get in thread $tid returns the right thing");
53  is($c, 1,  "get in thread $tid triggers magic");
54  my $d = eval { getdata $a, $wiz };
55  is($@, '',       "getdata in thread $tid doesn't croak");
56  is($d, 5 + $tid, "getdata in thread $tid returns the right thing");
57  is($c, 1,        "getdata in thread $tid doesn't trigger magic");
58  if ($dispell) {
59   $res = eval { dispell $a, $wiz };
60   is($@, '', "dispell in thread $tid doesn't croak");
61   is($c, 1,  "dispell in thread $tid doesn't trigger magic");
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   is($c, 1,  "get in thread $tid after dispell doesn't trigger magic");
67  }
68  return; # Ugly if not here
69 }
70
71 for my $dispell (1, 0) {
72  $destroyed = 0;
73  $sig = undef;
74
75  my @t = map { threads->create(\&try, $dispell) } 1 .. 2;
76  $t[0]->join;
77  $t[1]->join;
78
79  is($destroyed, (1 - $dispell) * 2, 'destructors');
80
81  $destroyed = 0;
82  $sig = Variable::Magic::gensig();
83
84  @t = map { threads->create(\&try, $dispell) } 1 .. 2;
85  $t[0]->join;
86  $t[1]->join;
87
88  is($destroyed, (1 - $dispell) * 2, 'destructors');
89 }