Ancient

 view release on metacpan or  search on metacpan

t/2026-doubly-cross-threads.t  view on Meta::CPAN

    my $list = doubly->new();
    $list->add('before');
    is($list->length, 1, 'list has 1 item before thread');

    my $t = threads->create(sub {
        # Do some work
        my $local_list = doubly->new();
        $local_list->add(1);
        return 1;
    });
    $t->join;

    is($list->length, 1, 'list still has 1 item after thread');
    is($list->data, 'before', 'list data unchanged');
    
    $list->add('after');
    is($list->length, 2, 'can still add to list');
};

# Test 4: Multiple threads each with their own lists
subtest 'multiple threads with own lists' => sub {
    plan tests => 1;

    my @results :shared;
    my @threads;
    
    for my $i (1..4) {
        push @threads, threads->create(sub {
            my $list = doubly->new();
            for my $j (1..10) {
                $list->add($j);
            }
            return $list->length;
        });
    }
    
    for my $t (@threads) {
        push @results, $t->join;
    }
    
    is_deeply(\@results, [10, 10, 10, 10], 'each thread had its own list');
};

# Test 5: Simple scalars can be passed via shared variables
subtest 'use shared variables for cross-thread communication' => sub {
    plan tests => 2;

    my $result :shared;
    
    my $list = doubly->new();
    $list->add(42);
    my $val = $list->data;  # Get the value before thread
    
    my $t = threads->create(sub {
        # Can't access $list, but can access shared $result
        $result = $val * 2;  # Use value captured before thread
        return 1;
    });
    $t->join;

    is($result, 84, 'shared variable updated by thread');
    is($list->data, 42, 'original list unchanged');
};

done_testing();



( run in 0.490 second using v1.01-cache-2.11-cpan-e1769b4cff6 )