AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 79318289
Accepted
I'mSRJ
I'mSRJ
Asked: 2024-12-31 02:10:21 +0800 CST2024-12-31 02:10:21 +0800 CST 2024-12-31 02:10:21 +0800 CST

在 Delphi 中使用队列实现多线程以限制同时运行的 n 个线程?

  • 772

我已经使用 Delphi 有一段时间了,现在正尝试在我的代码中实现多线程,要求如下:

  1. 每次只能运行 2 个线程。

  2. 其他任务应在队列中等待,并在线程可用时执行。

我尝试使用TParallel.For来实现这一点,但无法实现所需的行为。这是我的示例代码:

    type
       TMyRecord = record
         msg: String;
         sleep: Integer;
          end;

    var
      Form2: TForm2;

    implementation

    {$R *.dfm}

    procedure TForm2.Button1Click(Sender: TObject);
    var
      record1, record2, record3, record4, record5: TMyRecord;
      MyList: TList<TMyRecord>;
    begin
      // Initialize records
      record1.msg := 'Item1';
      record1.sleep := 10;

      record2.msg := 'Item2';
      record2.sleep := 10;

      record3.msg := 'Item3';
      record3.sleep := 3000;

      record4.msg := 'Item4';
      record4.sleep := 3000;

      record5.msg := 'Item5';
      record5.sleep := 100;

     MyList := TList<TMyRecord>.Create;
      try
        // Add records to the list
        MyList.Add(record1);
        MyList.Add(record2);
        MyList.Add(record3);
        MyList.Add(record4);
        MyList.Add(record5);

    // Use TParallel.For
    TParallel.For(0, MyList.Count - 1,
      procedure (i: Integer)
      var
        ListItem: TMyRecord;
      begin
        ListItem := MyList[i];

        TThread.Synchronize(nil,
          procedure
          begin
            Memo1.Lines.Add(ListItem.msg);
          end);

        Sleep(ListItem.sleep);
      end);

      finally
    MyList.Free;
  end;
end;

我也尝试使用TTask.Run和ThreadPool,但无法实现所需的行为。更新 - 这是我尝试使用 Threadpool 执行的操作

procedure TForm2.Button1Click(Sender: TObject);
var
  record1, record2, record3, record4, record5: TMyRecord;
  MyList: TList<TMyRecord>;
  ThreadPool: TThreadPool;
begin
  // Initialize records
  record1.msg := 'Item1';
  record1.sleep := 10;

  record2.msg := 'Item2';
  record2.sleep := 10;

  record3.msg := 'Item3';
  record3.sleep := 3000;

  record4.msg := 'Item4';
  record4.sleep := 3000;

  record5.msg := 'Item5';
  record5.sleep := 100;

  MyList := TList<TMyRecord>.Create;
  try
    // Add records to the list
    MyList.Add(record1);
    MyList.Add(record2);
    MyList.Add(record3);
    MyList.Add(record4);
    MyList.Add(record5);

    ThreadPool := TThreadPool.Create;
    ThreadPool.SetMaxWorkerThreads(2);

    // Iterate through the list and queue each work item with a copy of the record
    for var i := 0 to MyList.Count - 1 do
    begin
      var ListItem := MyList[i];

      ThreadPool.QueueWorkItem(
        procedure
        var
          LocalItem: TMyRecord;
        begin
          LocalItem := ListItem;

          TThread.Queue(nil,
            procedure
            begin
              Memo1.Lines.Add(LocalItem.msg);
              Sleep(LocalItem.sleep);  // Simulate the delay
            end);
        end);
    end;
  finally
    MyList.Free;
  end;
end;

此代码有问题-

  1. 它仅打印“item5”5次。
  2. 等待时间(睡眠)不起作用。

我该如何修改此代码以将同时运行的线程数限制为 2?并在线程可用时将其他任务排队执行?

multithreading
  • 2 2 个回答
  • 76 Views

2 个回答

  • Voted
  1. Best Answer
    Remy Lebeau
    2024-12-31T16:31:07+08:002024-12-31T16:31:07+08:00

    它仅打印“item5”5次。

    这意味着您排队的工作项正在捕获相同的内容TMyRecord,并且所有打印都是在该变量被分配列表中的最后一项之后发生的。

    即使您的循环正在使用本地内联变量,但考虑到匿名过程变量捕获的工作方式,它似乎忽略了内联。

    让匿名过程捕获循环内的变量的常见解决方案是将匿名过程移动到具有可捕获的输入参数的单独函数。

    等待时间(睡眠)不起作用。

    这可能是因为您是在主 UI 线程的上下文中执行睡眠,而不是在工作线程中,所以它们全速运行。

    尝试一些更像这样的事情:

    function MakeWorkItem(Item: TMyRecord): TProc;
    begin
      Result := procedure
        begin
          TThread.Queue(nil,
            procedure
            begin
              Form2.Memo1.Lines.Add(Item.msg);
            end
          );
          Sleep(Item.sleep);  // Simulate the delay 
        end;
    end; 
    
    procedure TForm2.Button1Click(Sender: TObject);
    var
      record1, record2, record3, record4, record5: TMyRecord;
      MyList: TList<TMyRecord>;
      ThreadPool: TThreadPool;
    begin
      // Initialize records
      record1.msg := 'Item1';
      record1.sleep := 10;
    
      record2.msg := 'Item2';
      record2.sleep := 10;
    
      record3.msg := 'Item3';
      record3.sleep := 3000;
    
      record4.msg := 'Item4';
      record4.sleep := 3000;
    
      record5.msg := 'Item5';
      record5.sleep := 100;
    
      MyList := TList<TMyRecord>.Create;
      try
        // Add records to the list
        MyList.Add(record1);
        MyList.Add(record2);
        MyList.Add(record3);
        MyList.Add(record4);
        MyList.Add(record5);
    
        ThreadPool := TThreadPool.Create;
        ThreadPool.SetMaxWorkerThreads(2);
    
        // Iterate through the list and queue each work item with a copy of the record
        for var i := 0 to MyList.Count - 1 do
        begin
          ThreadPool.QueueWorkItem(MakeWorkItem(MyList[i]));
        end;
      finally
        MyList.Free;
      end;
    end;
    

    或者,使用TParallel.For,只需将您想要的内容TThreadPool作为额外参数传递给它,例如:

    procedure TForm2.Button1Click(Sender: TObject);
    var
      record1, record2, record3, record4, record5: TMyRecord;
      MyList: TList<TMyRecord>;
      ThreadPool: TThreadPool;
    begin
      // Initialize records
      record1.msg := 'Item1';
      record1.sleep := 10;
    
      record2.msg := 'Item2';
      record2.sleep := 10;
    
      record3.msg := 'Item3';
      record3.sleep := 3000;
    
      record4.msg := 'Item4';
      record4.sleep := 3000;
    
      record5.msg := 'Item5';
      record5.sleep := 100;
    
      MyList := TList<TMyRecord>.Create;
      try
        // Add records to the list
        MyList.Add(record1);
        MyList.Add(record2);
        MyList.Add(record3);
        MyList.Add(record4);
        MyList.Add(record5);
    
        ThreadPool := TThreadPool.Create;
        ThreadPool.SetMaxWorkerThreads(2);
    
        // Use TParallel.For
        TParallel.For(0, MyList.Count - 1,
          procedure (i: Integer)
          var
            ListItem: TMyRecord;
          begin
            ListItem := MyList[i];
    
            TThread.Queue(nil,
              procedure
              begin
                Memo1.Lines.Add(ListItem.msg);
              end
            );
    
            Sleep(ListItem.sleep);
          end,
          ThreadPool
        );
      finally
        MyList.Free;
      end;
    end;
    
    • 3
  2. Darian Miller
    2024-12-31T13:43:37+08:002024-12-31T13:43:37+08:00

    您可以相当容易地使用专为此任务设计的TThreadedQueue 来完成此任务。

    我整理了一个小演示: https: //github.com/ideasawakened/DelphiKB/tree/master/Delphi%20Demos/TThreadedQueue/TwoClientThreads_MainThreadProducer

    • 创建一个TThreadedQueue
    • 衍生 2 个客户端工作线程
    • 单击按钮生成 TMyRecords 并使用 PushItem 将它们添加到队列中,然后 2 个工作线程将按顺序完成它们。

    示例代码。(+ 向表单添加 TButton/TMemo...)

    unit Unit1;
    
    interface
    
    uses
      Vcl.Controls,
      Vcl.Forms,
      Vcl.StdCtrls,
      System.Classes,
      System.Generics.Collections;
    
    type
    
      TMyRecord = record
        id:Integer;
        msg:string;
        sleep:Integer;
      end;
    
      TMyRecConsumerThread = class(TThread)
      private
        fQueue:TThreadedQueue<TMyRecord>;
        fThreadNumber:Integer;
      public
        constructor Create(const Queue:TThreadedQueue<TMyRecord>; const ThreadNumber:Integer);
    
        procedure Execute(); override;
      end;
    
    
      TMainForm = class(TForm)
        Memo1:TMemo;
        butProduce:TButton;
        procedure butProduceClick(Sender:TObject);
        procedure FormCreate(Sender:TObject);
        procedure FormDestroy(Sender:TObject);
      private const
        ConsumerThreadCount = 2;
    
        QueueDepth = 100;
        ProduceCount = 5;
        PushTimeout = 500;
        PopTimeout = 3000;
      private
        fQueue:TThreadedQueue<TMyRecord>;
        fRecId:Integer;
        fConsumers:TArray<TMyRecConsumerThread>;
        function CreateWorkItem:TMyRecord;
      end;
    
    var
      MainForm:TMainForm;
    
    implementation
    
    uses
      System.SysUtils,
      System.SyncObjs;
    
    {$R *.dfm}
    
    
    procedure TMainForm.FormCreate(Sender:TObject);
    begin
      ReportMemoryLeaksOnShutdown := True;
      fRecId := 1;
      butProduce.Caption := Format('Produce %d records', [ProduceCount]);
    
      fQueue := TThreadedQueue<TMyRecord>.Create(QueueDepth, PushTimeout, PopTimeout);
    
      SetLength(fConsumers, ConsumerThreadCount);
      for var i := 1 to ConsumerThreadCount do
      begin
        fConsumers[i-1] := TMyRecConsumerThread.Create(fQueue, i);
      end;
    end;
    
    
    procedure TMainForm.FormDestroy(Sender:TObject);
    begin
      for var ConsumerThread in fConsumers do
      begin
        ConsumerThread.Free;
      end;
      fQueue.DoShutDown;
      fQueue.Free;
    end;
    
    
    function TMainForm.CreateWorkItem:TMyRecord;
    begin
      Result := Default(TMyRecord);
      Result.id := fRecId;
      Result.sleep := Random(PopTimeout div 2);
      Result.msg := Format('Task %d sleeping %dms', [fRecId, Result.sleep]);
    
      Memo1.Lines.Add(Format('Produced Task %d to sleep %dms', [fRecId, Result.sleep]));
      Inc(fRecId);
    end;
    
    
    //click the button one or more times to queue up some work items
    procedure TMainForm.butProduceClick(Sender:TObject);
    var
      wr:TWaitResult;
    begin
      for var i := 1 to ProduceCount do
      begin
        wr := fQueue.PushItem(CreateWorkItem);
        Assert(wr = TWaitResult.wrSignaled);  // IRL deal with <> wrSignaled (e.g., timeout if queue is full)
      end;
    end;
    
    
    constructor TMyRecConsumerThread.Create(const Queue:TThreadedQueue<TMyRecord>; const ThreadNumber:Integer);
    begin
      fQueue := Queue;
      fThreadNumber := ThreadNumber;
      inherited Create({CreateSuspended=}False);
    end;
    
    
    procedure TMyRecConsumerThread.Execute;
    var
      wr:TWaitResult;
      r:TMyRecord;
    begin
      NameThreadForDebugging(Format('Consumer%d', [fThreadNumber]));
    
      while (not Terminated) and (not fQueue.ShutDown) do
      begin
        wr := fQueue.PopItem(r);
        if (wr = wrSignaled) then
        begin
          if r.id > 0 then //Note: if 0, then PopItem was signalled as Queue was told to shut down (rec will be "Default(TMyRecord)")
          begin
            TThread.Synchronize(nil,
              procedure
              begin
                MainForm.Memo1.Lines.Add(Format('Consumed %s', [r.msg]));
              end);
            sleep(r.sleep); //would be better to have an abortable sleep using an TEvent
          end;
        end;
      end;
    end;
    
    
    end.
    
    • 2

相关问题

  • JMeter 属性并发写入

  • 如何在生成的 tauri 异步运行时线程中使用托管 Tauri 状态变量?

  • 主线程中额外的 println 导致 Rust 执行不同的结果

  • 从缓存中刷新低争用原子的最佳方式?

  • Rust:遍历文件夹并打开每个文件

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行?

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    何时应使用 std::inplace_vector 而不是 std::vector?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Martin Hope
    Aleksandr Dubinsky 为什么 InetAddress 上的 switch 模式匹配会失败,并出现“未涵盖所有可能的输入值”? 2024-12-23 06:56:21 +0800 CST
  • Martin Hope
    Phillip Borge 为什么这个简单而小的 Java 代码在所有 Graal JVM 上的运行速度都快 30 倍,但在任何 Oracle JVM 上却不行? 2024-12-12 20:46:46 +0800 CST
  • Martin Hope
    Oodini 具有指定基础类型但没有枚举器的“枚举类”的用途是什么? 2024-12-12 06:27:11 +0800 CST
  • Martin Hope
    sleeptightAnsiC `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它? 2024-11-09 07:18:53 +0800 CST
  • Martin Hope
    The Mad Gamer 何时应使用 std::inplace_vector 而不是 std::vector? 2024-10-29 23:01:00 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST
  • Martin Hope
    MarkB 为什么 GCC 生成有条件执行 SIMD 实现的代码? 2024-02-17 06:17:14 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve