控制多個Thread-Process 執行[利用Timer與Semaphore] |
|
chris_shieh
高階會員 ![]() ![]() ![]() ![]() 發表:46 回覆:308 積分:240 註冊:2004-04-26 發送簡訊給我 |
控制多個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 |
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |