File: 10_threads.t

package info (click to toggle)
libdata-clone-perl 0.006-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 208 kB
  • sloc: perl: 669; makefile: 8; ansic: 5
file content (108 lines) | stat: -rw-r--r-- 2,248 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!perl -w

use strict;
use constant HAS_THREADS => eval{ require threads };
use if !HAS_THREADS, 'Test::More', skip_all => 'This test requires threads';
use Test::More;

use warnings FATAL => 'all';

use Data::Clone;
use Time::HiRes qw(usleep);

{
    package MyBase;

    sub new {
        my $class = shift;
        return bless {@_}, $class;
    }

    package MyNoclonable;
    our @ISA = qw(MyBase);

    package MyClonable;
    use Data::Clone;
    our @ISA = qw(MyBase);

    package MyCustomClonable;
    use Data::Clone qw(data_clone);
    our @ISA = qw(MyBase);

    sub clone {
        my $cloned = data_clone(@_);
        $cloned->{bar} = 42;
        return $cloned;
    }

    package CreateThreadsInClone;
    use Data::Clone qw(data_clone);
    our @ISA = qw(MyBase);

    sub clone {
        my $cloned = data_clone(@_);
        $cloned->{bar} = threads->create(sub{ data_clone([42]) })->join();
        return $cloned;
    }
}

my @threads;
for(1 .. 3){

    push @threads, threads->create(sub{
        usleep 10;;

        my $o = MyNoclonable->new(foo => 10);
        my $c = do{
            local $Data::Clone::ObjectCallback = sub{ $_[0] };
            clone($o);
        };

        is $c, $o, "tid - " . threads->tid;
        $c->{foo}++;
        is $o->{foo}, 11, 'noclonable';

        usleep 10;

        $o = MyClonable->new(foo => 10);
        $c = clone($o);
        isnt $c, $o;
        $c->{foo}++;
        is $o->{foo}, 10, 'clonable';

        usleep 10;

        $o = MyCustomClonable->new(foo => 10);
        $c = clone($o);
        isnt $c, $o;
        $c->{foo}++;
        is $o->{foo}, 10, 'clonable';
        is_deeply $c, { foo => 11, bar => 42 }, 'custom clone()';

        usleep 10;

        $o = MyCustomClonable->new(foo => MyClonable->new(bar => 42));
        $c = clone($o);

        $c->{foo}{bar}++;

        is $o->{foo}{bar}, 42, 'clone() is reentrant';
        is $c->{foo}{bar}, 43;

        $o = CreateThreadsInClone->new(foo => 50);
        $c = clone($o);

        usleep 10;

        is $c->{foo}, 50;
        is_deeply $c->{bar}, [42], 'threads->create in clone()';

        return threads->tid;
    });
}

foreach my $thr(@threads){
    pass "\$thr->join: " . $thr->join;
}

done_testing;