xref: /openbsd-src/gnu/usr.bin/perl/cpan/Memoize/t/threadsafe.t (revision f2a19305cfc49ea4d1a5feb55cd6c283c6f1e031)
1use strict; use warnings;
2
3use Memoize qw(memoize unmemoize);
4use Test::More
5	("$]" < 5.009 || "$]" >= 5.010001) && eval { require threads; 1 }
6		? ( tests => 8 )
7		: ( skip_all => $@ );
8
9my $i;
10sub count_up { ++$i }
11
12memoize('count_up');
13my $cached = count_up();
14
15is count_up(), $cached, 'count_up() is memoized';
16
17my $got = threads->new(sub {
18	local $@ = '';
19	my $v = eval { count_up() };
20	+{ E => $@, V => $v };
21})->join;
22
23is $got->{E}, '', 'calling count_up() in another thread works';
24is $got->{V}, $cached, '... and returns the same result';
25is count_up(), $cached, '... whereas count_up() on the main thread is unaffected';
26
27$got = threads->new(sub {
28	local $@ = '';
29	my $u = eval { unmemoize('count_up') };
30	my $v = eval { count_up() };
31	+{ E => $@, U => $u, V => $v };
32})->join;
33
34is $got->{E}, '', 'unmemoizing count_up() in another thread works';
35is ref($got->{U}), 'CODE', '... and returns a coderef as expected';
36is $got->{V}, 1+$cached, '... and does in fact unmemoize the function';
37is count_up(), $cached, '... whereas count_up() on the main thread is unaffected';
38