線上訂房服務-台灣趴趴狗聯合訂房中心
發文 回覆 瀏覽次數:2144
推到 Plurk!
推到 Facebook!

控制多個Thread-Process 執行[利用Timer與Semaphore]

 
chris_shieh
高階會員


發表:46
回覆:308
積分:240
註冊:2004-04-26

發送簡訊給我
#1 引用回覆 回覆 發表時間:2005-01-06 12:46:33 IP:61.30.xxx.xxx 未訂閱
控制多個Thread-Process 執行[利用Timer與Semaphore]    1.利用同步機制 Semaphore [Main Thread: Form1]
CONST
  MAX_THREAD_COUNT=10;
  TOTAL_JOB_COUNT=1000;
  
var //全域變數
  Form1:TForm1;
  SemaphoreHandle:THandle;                 procedure Form1.ThreadDone(Sender:TObject);
begin
  ...
  ...  
  ReleaseSemaphore(SemaphoreHandle, 1, nil); //signaled waiting
end;    procedure Form1.StartThreadExec;
var
  mythread:TMyThread;
  i:inetger;
begin
  SemaphoreHandle := CreateSemaphore(nil, MAX_THREAD_COUNT, MAX_THREAD_COUNT, 'MySemaphore');  
  for i:=1 to TOTAL_JOB_COUNT do
  begin
     //在這裡等別的thread 完成 但主程式UI 可能會Hang住 要注意 可以另外用一個Thread 來作這些事情避免
     WaitForSingleObject(SemaphoreHandle, INFINITE);
     mythread:=TMyThread.Create(True); //Create with Suspended
     mythread.OnTerminate:=ThreadDone; //如果是在Thread 裡面等待就不需要這個了
     mythread.Resume:=True; //Start running thread
  end; 
end;
[TMyThread:]
const
  SYNCHRONIZE = $00100000;
  STANDARD_RIGHTS_REQUIRED = $000F0000;
  SEMAPHORE_MODIFY_STATE = $0002;
  SEMAPHORE_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED or SYNCHRONIZE or $3);    procedure TMyThread.Execute;
var
  SemaphoreHandle: THandle;      // holds the semaphore handle  
begin
  //或是在Thread這裡等, 但是要注意thread 會先執行起來等待,
  //SemaphoreHandle := OpenSemaphore(SEMAPHORE_ALL_ACCESS, FALSE, 'MySemaphore'); //Open a handle to the semaphore
  //WaitForSingleObject(SemaphoreHandle, INFINITE); 
  
  {do MyThread things after here}
  ...
  ...                               
  //ReleaseSemaphore(SemaphoreHandle, 1, nil);
  //CloseHandle(SemaphoreHandle);   
end;
           2.在Main thread Timer裡面處理    CONST
  MAX_THREAD_COUNT=10;
  TOTAL_JOB_COUNT=1000;
  
var //全域變數
  Form1:TForm1;
  threadCount, totalCount:integer;    procedure Form1.ThreadDone(Sender:TObject);
begin
  ...
  ...  
  Dec(threadCount);
end;    //以Timer方式 來啟動 Thread : Timer 間隔可視情況調整
procedure Form1.Timer1Timer(Sender:TObject);
var
  mythread:TMyThread;
begin
  if totalCount<=TOTAL_JOB_COUNT then
  begin
     if threadCount        發表人 - chris_shieh 於 2005/01/06  13:24:47    發表人 - chris_shieh 於 2005/01/06  13:25:33
        
系統時間:2024-06-30 2:50:10
聯絡我們 | Delphi K.Top討論版
本站聲明
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。
2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。
3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇!