File: threadsafe.t

package info (click to toggle)
perl 5.42.0-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 128,392 kB
  • sloc: perl: 534,963; ansic: 240,563; sh: 72,042; pascal: 6,934; xml: 2,428; yacc: 1,360; makefile: 1,197; cpp: 208; lisp: 1
file content (37 lines) | stat: -rw-r--r-- 1,080 bytes parent folder | download | duplicates (2)
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
use strict; use warnings;

use Memoize qw(memoize unmemoize);
use Test::More
	("$]" < 5.009 || "$]" >= 5.010001) && eval { require threads; 1 }
		? ( tests => 8 )
		: ( skip_all => $@ );

my $i;
sub count_up { ++$i }

memoize('count_up');
my $cached = count_up();

is count_up(), $cached, 'count_up() is memoized';

my $got = threads->new(sub {
	local $@ = '';
	my $v = eval { count_up() };
	+{ E => $@, V => $v };
})->join;

is $got->{E}, '', 'calling count_up() in another thread works';
is $got->{V}, $cached, '... and returns the same result';
is count_up(), $cached, '... whereas count_up() on the main thread is unaffected';

$got = threads->new(sub {
	local $@ = '';
	my $u = eval { unmemoize('count_up') };
	my $v = eval { count_up() };
	+{ E => $@, U => $u, V => $v };
})->join;

is $got->{E}, '', 'unmemoizing count_up() in another thread works';
is ref($got->{U}), 'CODE', '... and returns a coderef as expected';
is $got->{V}, 1+$cached, '... and does in fact unmemoize the function';
is count_up(), $cached, '... whereas count_up() on the main thread is unaffected';