gpt4 book ai didi

multithreading - Perl线程模型

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

  • 我有100多个任务要做,我可以循环执行,但是
  • 会很慢
  • 我想通过线程来完成这些工作,比如说10个线程
  • 作业之间没有依赖关系,每个作业都可以独立运行,如果
  • 失败则停止
  • 我希望这些线程接我的工作并执行,总共不应超过10个线程,否则可能会损害服务器
  • 这些线程会继续执行作业,直到所有
  • 完成为止
  • 超时时停止线程中的作业

  • 我正在Internet上搜索有关此信息 Threads::PoolThreads::Queue ...
    但是我不能确定哪一种对我的情况更好。有人可以给我一些建议吗?

    最佳答案

    您可以使用Thread::Queue和线程。

    进程之间的IPC(线程之间的通信)更加容易。

    To fork or not to fork?

    use strict;
    use warnings;

    use threads;
    use Thread::Queue;

    my $q = Thread::Queue->new(); # A new empty queue

    # Worker thread
    my @thrs = threads->create(sub {
    while (my $item = $q->dequeue()) {
    # Do work on $item
    }
    })->detach() for 1..10;#for 10 threads
    my $dbh = ...
    while (1){
    #get items from db
    my @items = get_items_from_db($dbh);
    # Send work to the thread
    $q->enqueue(@items);
    print "Pending items: "$q->pending()."\n";
    sleep 15;#check DB in every 15 secs
    }

    关于multithreading - Perl线程模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21567631/

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