]> git.vpit.fr Git - perl/modules/Scope-Upper.git/blob - t/69-uplevel-threads.t
6ea386aac9d54e13c0c554614744a2906f6693a7
[perl/modules/Scope-Upper.git] / t / 69-uplevel-threads.t
1 #!perl -T
2
3 use strict;
4 use warnings;
5
6 sub skipall {
7  my ($msg) = @_;
8  require Test::More;
9  Test::More::plan(skip_all => $msg);
10 }
11
12 use Config qw<%Config>;
13
14 BEGIN {
15  my $force = $ENV{PERL_SCOPE_UPPER_TEST_THREADS} ? 1 : !1;
16  my $t_v   = $force ? '0' : '1.67';
17  skipall 'This perl wasn\'t built to support threads'
18                                                     unless $Config{useithreads};
19  skipall 'perl 5.13.4 required to test thread safety'
20                                               unless $force or "$]" >= 5.013004;
21  skipall "threads $t_v required to test thread safety"
22                                               unless eval "use threads $t_v; 1";
23 }
24
25 use Test::More;
26
27 use Scope::Upper qw<uplevel UP SU_THREADSAFE>;
28
29 my $num;
30
31 BEGIN {
32  skipall 'This Scope::Upper isn\'t thread safe' unless SU_THREADSAFE;
33  plan tests => 3 + ($num = 30) * 3;
34  defined and diag "Using threads $_" for $threads::VERSION;
35  if (eval "use Time::HiRes; 1") {
36   defined and diag "Using Time::HiRes $_" for $Time::HiRes::VERSION;
37   *usleep = \&Time::HiRes::usleep;
38  } else {
39   diag 'Using fallback usleep';
40   *usleep = sub {
41    my $s = int($_[0] / 2.5e5);
42    sleep $s if $s;
43   };
44  }
45 }
46
47 sub depth {
48  my $depth = 0;
49  while (1) {
50   my @c = caller($depth);
51   last unless @c;
52   ++$depth;
53  }
54  return $depth - 1;
55 }
56
57 is depth(),                           0, 'check top depth';
58 is sub { depth() }->(),               1, 'check subroutine call depth';
59 is do { local $@; eval { depth() } }, 1, 'check eval block depth';
60
61 our $z;
62
63 sub cb {
64  my $d   = splice @_, 1, 1;
65  my $p   = shift;
66  my $tid = pop;
67  is depth(), $d - 1, "$p: correct depth inside";
68  $tid, @_, $tid + 2
69 }
70
71 sub up1 {
72  my $tid  = threads->tid();
73  local $z = $tid;
74  my $p    = "[$tid] up1";
75
76  usleep rand(1e6);
77
78  my @res = (
79   -2,
80   sub {
81    my @dummy = (
82     -1,
83     sub {
84      my $d = depth();
85      my @ret = &uplevel(\&cb => ($p, $d, $tid + 1, $tid) => UP);
86      is depth(), $d, "$p: correct depth after uplevel";
87      @ret;
88     }->(),
89     1
90    );
91   }->(),
92   2
93  );
94
95  is_deeply \@res, [ -2, -1, $tid .. $tid + 2, 1, 2 ], "$p: returns correctly";
96 }
97
98 $_->join for map threads->create(\&up1), 1 .. $num;