Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/image-processing/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 如何在Perl中将共享数据传递给线程?_Multithreading_Perl - Fatal编程技术网

Multithreading 如何在Perl中将共享数据传递给线程?

Multithreading 如何在Perl中将共享数据传递给线程?,multithreading,perl,Multithreading,Perl,为什么数据没有在线程中共享?您误解了threads::shared的作用。它不允许跨词法范围访问变量。如果希望thrsub影响$s,则必须在创建线程时传递对它的引用 use threads; use threads::shared; sub test { my $s :shared = 22; my $thread = threads->new(\&thrsub); $thread->join(); print $s; } sub th

为什么数据没有在线程中共享?

您误解了
threads::shared
的作用。它不允许跨词法范围访问变量。如果希望
thrsub
影响
$s
,则必须在创建线程时传递对它的引用

use threads;
use threads::shared;

sub test {
    my $s :shared = 22;
    my $thread = threads->new(\&thrsub);

    $thread->join();
    print $s;

}

sub thrsub {
    $s = 33;
}

test;

您误解了
threads::shared
的作用。它不允许跨词法范围访问变量。如果希望
thrsub
影响
$s
,则必须在创建线程时传递对它的引用

use threads;
use threads::shared;

sub test {
    my $s :shared = 22;
    my $thread = threads->new(\&thrsub);

    $thread->join();
    print $s;

}

sub thrsub {
    $s = 33;
}

test;

它共享变量,但您访问的变量与共享的变量不同。(
使用严格;
会告诉您在这种情况下有不同的变量。始终使用
使用严格;使用警告;
)修复方法是使用单个变量

use strict; use warnings;
use threads;
use threads::shared;

sub test {
    my $s = 22;
    my $s_ref = share $s;
    my $thread = threads->new(\&thrsub, $s_ref);

    $thread->join();
    print $s;

}

sub thrsub {
    my $s_ref = shift;
    $$s_ref = 33;
    return;
}

test;

它共享变量,但您访问的变量与共享的变量不同。(
使用严格;
会告诉您在这种情况下有不同的变量。始终使用
使用严格;使用警告;
)修复方法是使用单个变量

use strict; use warnings;
use threads;
use threads::shared;

sub test {
    my $s = 22;
    my $s_ref = share $s;
    my $thread = threads->new(\&thrsub, $s_ref);

    $thread->join();
    print $s;

}

sub thrsub {
    my $s_ref = shift;
    $$s_ref = 33;
    return;
}

test;