multithreading - Perl线程模型

标签 multithreading perl

  • 我有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/

    相关文章:

    在 JPanel 中实现 Runnable 时出现 java.lang.StackOverflowError - Java Swing

    C - 等待多个线程终止

    java - 编写复习线程的最佳方法

    c - futex 工具返回了意外的错误代码并中止

    perl - 如何在 Perl 的 system() 中检查管道中第一个程序的状态?

    Perl split() 不删除定界符

    C#:异步回调 - 回调方法的处理是否会阻塞应用程序?

    perl - 如果我在此之前阅读用户输入,为什么 perl 不能就地编辑工作?

    perl - 动态函数注入(inject)到 Text::Template 命名空间

    mysql - 为 mySQL 数据库实现定期匹配系统的正确方法是什么?