gpt4 book ai didi

perl - 在 Perl 中执行多线程时应该查看哪些模块?

转载 作者:行者123 更新时间:2023-12-04 09:03:11 29 4
gpt4 key购买 nike

在 Perl 中执行多线程时应该查看哪些模块?

我正在寻找性能相当低的东西;我希望线程同时运行多个工作人员,每个工作人员都睡不同的时间。

最佳答案

您可能不想使用多线程的原因有很多。但是,如果您确实想要多线程,则以下代码可能是一个有用的示例。它创建许多作业,将它们放入线程安全队列中,然后启动一些线程,从队列中提取作业并完成它们。每个线程都在循环中不断地从队列中拉出作业,直到它看不到更多作业为止。该程序等待所有线程完成,然后打印它在作业上花费的总时间。

#!/usr/bin/perl

use threads;
use Thread::Queue;
use Modern::Perl;

my $queue= Thread::Queue->new;
my $thread_count= 4;
my $job_count= 10;
my $start_time= time;
my $max_job_time= 10;

# Come up with some jobs and put them in a thread-safe queue. Each job
# is a string with an id and a number of seconds to sleep. Jobs consist
# of sleeping for the specified number of seconds.
my @jobs= map {"$_," . (int(rand $max_job_time) + 1)} (1 .. $job_count);
$queue->enqueue(@jobs);

# List the jobs
say "Jobs IDs: ", join(", ", map {(split /,/, $_)[0]} @jobs);

# Start the threads
my @threads= map {threads->create(sub {function($_)})} (1 .. $thread_count);

# Wait for all the threads to complete their work
$_->join for (@threads);

# We're all done
say "All done! Total time: ", time - $start_time;

# Here's what each thread does. Each thread starts, then fetches jobs
# from the job queue until there are no more jobs in the queue. Then,
# the thread exists.
sub function {
my $thread_id= shift;
my ($job, $job_id, $seconds);
while($job= $queue->dequeue_nb) {
($job_id, $seconds)= split /,/, $job;
say "Thread $thread_id starting on job $job_id ",
"(job will take $seconds seconds).";
sleep $seconds;
say "Thread $thread_id done with job $job_id.";
}
say "No more jobs for thread $thread_id; thread exiting.";
}

关于perl - 在 Perl 中执行多线程时应该查看哪些模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1480637/

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