This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Tests shared hashes.
[perl5.git] / ext / threads / shared / t / hv_simple.t
1
2 BEGIN {
3 #    chdir 't' if -d 't';
4 #    push @INC ,'../lib';
5     require Config; import Config;
6     unless ($Config{'useithreads'}) {
7         print "1..0 # Skip: no useithreads\n";
8         exit 0;
9     }
10 }
11
12
13 sub ok {
14     my ($id, $ok, $name) = @_;
15
16     # You have to do it this way or VMS will get confused.
17     print $ok ? "ok $id - $name\n" : "not ok $id - $name\n";
18
19     printf "# Failed test at line %d\n", (caller)[2] unless $ok;
20
21     return $ok;
22 }
23
24
25
26 use ExtUtils::testlib;
27 use strict;
28 BEGIN { print "1..21\n" };
29 use threads;
30 use threads::shared;
31 ok(1,1,"loaded");
32 my %hash;
33 share(%hash);
34 $hash{"foo"} = "bar";
35 ok(2,$hash{"foo"} eq "bar","Check hash get");
36 threads->create(sub { $hash{"bar"} = "thread1"})->join();
37 threads->create(sub { ok(3,$hash{"bar"} eq "thread1", "Check thread get and write")})->join();
38 {
39     my $foo = delete($hash{"bar"});
40     ok(4, $foo eq "thread1", "Check delete, want 'thread1' got '$foo'");
41     $foo = delete($hash{"bar"});
42     ok(5, $foo == undef, "Check delete on empty value");
43 }
44 ok(6, keys %hash == 1, "Check keys");
45 $hash{"1"} = 1;
46 $hash{"2"} = 2;
47 $hash{"3"} = 3;
48 ok(7, keys %hash == 4, "Check keys");
49 ok(8, exists($hash{"1"}) == 1, "Exist on existing key");
50 ok(9, exists($hash{"4"}) == undef, "Exists on non existing key");
51 my %seen;
52 foreach my $key ( keys %hash) {
53     $seen{$key}++;
54 }
55 ok(10, $seen{1} == 1, "Keys..");
56 ok(11, $seen{2} == 1, "Keys..");
57 ok(12, $seen{3} == 1, "Keys..");
58 ok(13, $seen{"foo"} == 1, "Keys..");
59 threads->create(sub { %hash = () })->join();
60 ok(14, keys %hash == 0, "Check clear");
61 ok(15, threads::shared::_thrcnt(\%hash) == 1, "thrcnt");
62 threads->create(sub { ok(16, threads::shared::_thrcnt(\%hash) == 2, "thrcnt is up")})->join();
63 ok(17, threads::shared::_thrcnt(\%hash) == 1, "thrcnt is down");
64
65         my $test;
66         my $test2;
67         share($test);
68         $test = \%hash;
69         $test2 = \%hash;
70         ok(18, threads::shared::_thrcnt(\%hash) == 2, "thrcnt is up on shared reference");
71         $test = "bar";
72         ok(19 , threads::shared::_thrcnt(\%hash) == 1, "thrcnt is down when shared reference is dropped");
73         $test = $test2;
74         ok(20, threads::shared::_thrcnt(\%hash) == 2, "thrcnt is up on shared reference");
75 }
76 ok(21 , threads::shared::_thrcnt(\%hash) == 1, "thrcnt is down when shared reference is killed");