]> git.vpit.fr Git - perl/modules/Scope-Upper.git/blob - t/79-uid-threads.t
Implement uid() and validate_uid()
[perl/modules/Scope-Upper.git] / t / 79-uid-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<uid validate_uid UP HERE SU_THREADSAFE>;
28
29 my $num;
30
31 BEGIN {
32  skipall 'This Scope::Upper isn\'t thread safe' unless SU_THREADSAFE;
33  plan tests => ($num = 30) * 5 + 1;
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 my $top = uid;
48
49 sub cb {
50  my $tid  = threads->tid();
51
52  my $here = uid;
53  my $up;
54  {
55   $up = uid HERE;
56   is uid(UP), $here, "uid(UP) == \$here in block (in thread $tid)";
57  }
58
59  is uid(UP), $top, "uid(UP) == \$top (in thread $tid)";
60
61  usleep rand(1e6);
62
63  ok validate_uid($here), "\$here is valid (in thread $tid)";
64  ok !validate_uid($up),  "\$up is no longer valid (in thread $tid)";
65
66  return $here;
67 }
68
69 my %uids;
70
71 for my $thread (map threads->create(\&cb), 1 .. $num) {
72  my $tid = $thread->tid;
73  my $uid = $thread->join;
74  ++$uids{$uid};
75  ok !validate_uid($uid), "\$here is no longer valid (out of thread $tid)";
76 }
77
78 is scalar(keys %uids), $num, 'all the UIDs were different';