线程池类开发

use*_*184 -1 delphi multithreading

我运行一个多线程的应用程序,我想限制我的机器上的线程数量代码概念目前是这样的(它只是一个显示背后的主要想法的一个空洞)

     //  a List with all the threads I have  
     class MyTHreadList = List<TMyCalcThread>;
     //  a pool class, check how many threads are active 
     //  try to start additions threads once the nr. of running THreads
     //  is below the max_thread_value_running
     class MyTheardPool = Class 
               ThreadList :  MyTHreadList;
                StillRunningTHreads : Integer;
                StartFromThreadID : Integer;
               end; 

     var aTHreadList : MyTHreadList;


      procedure  MainForm.CallCreateThreadFunction( < THREAD PARAMS > );
      begin
            //   just create but do not start here 
            MyTHread := TMyCalcThread.create ( < THREAD PARAMS > ); 
            MyTHread.Onterminate := What_To_do;  
            //   add all threads to a list 
            aTHreadList.add(MyTHread);
      end;  
      /// (A)
      procedure  MainForm.What_To_do () 
      var start : Integer;
      begin
             max_thread_value_running := max_thread_value_running -1;

            if max_thread_value_running < max_thread_count then 
                  begin
                   start := max_thread_count - max_thread_value_running;
                     startThereads(start,StartFromThreadID)
                  end;
      end;

      procedure MainForm.startThereads (HowMany , FromIndex : Integer);
      var   i  : INteger; 
      begin
           for I := FromIndex to HowMany + FromIndexdo 
                begin
                   //  thread[i].start
                end;
      end;



      MainForm.Button ();

      ///  main VCL form , create threats
      for i := 0 to allTHreads do
             begin
               CallCreateTHreadFunction( < THREAD PARAMS > );
             end; 

     ......

     ///  (B)
     while  StillRunningTHreads > 0 do
             begin
                Application.processmessages;
             end;
Run Code Online (Sandbox Code Playgroud)

完整的想法是一个带有线程的小列表,在每个单独的线程终止步骤中,我更新正在运行的线程的数量并开始现在可能的最大值.新线程的数量.(A)而不是函数WaitforSingleObject()....我在最后做一个循环来等待所有线程完成执行.(B)

从代码设计我没有在网上找到任何完整的例子,我可能接近一个虚拟设计或者我会遇到一些我现在没有考虑的麻烦.欢迎任何关于dieign或更好的类设计的评论.

Mar*_*mes 7

不要试图微观管理这样的线程.只是不要.要么使用Win API线程池调用,要么从生产者 - 消费者队列和TThread实例创建自己的线程池.

当任务完成时,我建议工作线程调用任务类的'OnCompletion'TNotifyEvent,并将任务作为参数.可以由任务的发布者将其设置为他们可能希望的任何内容,例如.postMessaging任务实例到GUI线程显示.

微管理线程,不断创建/等待/终止/销毁,Application.processmessages循环等是非常可怕的,几乎肯定会在某些时候出错.

在GUI事件处理程序中等待任何事情都很糟糕.GUI系统是状态机,您不应该在其中等待.如果要从GUI线程发出任务,请执行此操作但不要等待它 - 将其关闭并忘记它直到完成并将其发回消息处理程序.