關於使用多個Thread的問題? |
答題得分者是:Zard
|
nlj859
資深會員 發表:139 回覆:375 積分:322 註冊:2004-03-20 發送簡訊給我 |
我有3個Thread,其Thread1和Thread3是一樣的,如下:
Thread1 __fastcall add1Thread::add1Thread(bool CreateSuspended) : TThread(CreateSuspended) { a=0; } void __fastcall add1Thread::Execute() { //---- Place thread code here ---- while (!Terminated) { Synchronize(add1); Sleep(1000); } } void __fastcall add1Thread::add1(void) { a ; Form1->Memo1->Lines->Add(a); } Thread2 __fastcall add2Thread::add2Thread(bool CreateSuspended) : TThread(CreateSuspended) { b=0; } void __fastcall add2Thread::Execute() { //---- Place thread code here ---- while (!Terminated) { Synchronize(add2); Sleep(1000); } } void __fastcall add2Thread::add2(void) { int x,y; for (int i=0;i<65000;i ) { for (int j=0;j<10;j ) { y = random(i j); x = random(i j); Application->ProcessMessages(); } } b ; Form1->Memo2->Lines->Add(b); } Thread3 __fastcall add3Thread::add3Thread(bool CreateSuspended) : TThread(CreateSuspended) { c=0; } void __fastcall add3Thread::Execute() { //---- Place thread code here ---- while (!Terminated) { Synchronize(add3); Sleep(1000); } } void __fastcall add3Thread::add3(void) { c ; Form1->Memo3->Lines->Add(c); }我將此程式執行的結果是:每次都要等Thread2執行過一次之後,Thread1和Thread3才會出來一筆,請問我要怎麼在Thread2執行當中,Thread1和Thread3也可以同時執行? 謝謝. |
Zard
尊榮會員 發表:24 回覆:396 積分:539 註冊:2003-11-26 發送簡訊給我 |
您每一個Thread內都有使用Synchronize(), 因為Synchronize()會把要做的事交給Main Thread來做, 所以雖然您有三個Thread, 但是在做事的都是Main Thread, Synchronize的解釋如下: type TThreadMethod = procedure of object;
procedure Synchronize(Method: TThreadMethod); Description Synchronize causes the call specified by Method to be executed using the main VCL thread, thereby avoiding multi-thread conflicts. If you are unsure whether a method call is thread-safe, call it from within the main VCL thread by passing it to the Synchronize method. Execution of the thread is suspended while Method is executing in the main VCL thread. 每一個Thread都要等待目前在使用Main Thread的Thread做完才可以繼續做下去, 這應該就是造成Thread1, Thread3, 總是在Thread2之後的原因. 如果要三個Thread同時執行, 就不能用Synchronize().
|
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |