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