gpt4 book ai didi

multithreading - 我可以在 perl 中重用加入的线程吗?

转载 作者:行者123 更新时间:2023-12-03 13:19:52 26 4
gpt4 key购买 nike

我有一个运行多个线程并将它们推送到线程列表的模块。

前任:

#!/usr/bin/perl

#test_module.pm

package test_module;

use strict;
use warnings;
use threads;

sub main {

my $max_threads = 10;
my @threads = ();

# create threads
while (scalar @threads < $max_threads) {
my $thread = threads->new(\&thread_sub);
push @threads, $thread;
}

# join threads
for my $thread (@threads) {
$thread->join();
}
}

sub thread_sub {
my $id = threads->tid();
print "I am in thread $id\n";
}

1;

问题是我从一个 Perl 脚本多次调用这个模块,而不是消除旧线程并创建新线程,线程 ID 只是不断增加。我听说如果你没有正确地摆脱 Perl 中的旧线程,这会导致内存泄漏并减慢你的程序,这是真的吗?我的旧线程中的数据是否只是在内存中占用空间?

如果是这样,这可能会成为一个大问题,因为我的脚本将成为一个更大的程序的一部分,该程序可能会生成数百或数千个线程,所有这些线程即使在使用完之后也会占用内存。我怎样才能阻止这种情况发生?我的线程可以重复使用吗?

这是一个示例脚本,它将调用模块并显示即使我加入了旧线程,线程将如何继续增加(我认为“加入”是你在它们之后清理的方式,我做错了什么吗?)将使用此脚本 我不能承受旧线程的内存占用空间。

前任:
#!/usr/bin/perl

#testing.pl

use strict;
use warnings;
use test_module;

test_module::main();
test_module::main();
test_module::main();

system 'pause';

谢谢!

最佳答案

不要担心线程 ID 会增加——这并不意味着正在运行的线程数会增加。一旦一个线程是join ed 它已完成执行并被终止。

然而,连续重生线程也不理想——创建线程在 perl 中并不是一个特别轻量级的操作。因此,如果您必须做类似的事情,并且特别关注效率 - 请查看 fork()反而。

我发现我倾向于使用“工作线程”模型,使用 Thread::Queue :

my $processing_q = Thread::Queue -> new();

sub worker_thread {
while ( my $item = $processing_q -> dequeue() ) {
# do stuff to $item
}
}

for ( 1 .. $num_threads ) {
my $thr = threads -> create ( \&worker_thread );
}

$processing_q -> enqueue ( @generic_list_of_things );
$processing_q -> end;

foreach my $thread ( threads -> list() ) {
$thread -> join();
}

这会将一批项目送入队列,并且您的工作线程将一次处理一个 - 这意味着您可以运行一个合理的数字,而不必连续重生。

作为替代方案 - 看看 Parallel::ForkManager - 叉式并行处理最初可能看起来违反直觉,但 fork()是 Unix 系统上的 native 系统调用,因此它往往会得到更好的优化。

关于multithreading - 我可以在 perl 中重用加入的线程吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25937484/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com