Thread 與 Process 資源共享是否需要 Synchronize |
缺席
|
linly
一般會員 發表:42 回覆:37 積分:15 註冊:2007-10-07 發送簡訊給我 |
看了C++ Builder 完全攻略,上面提到,若你的 process 產生多個 threads,且彼此有共享資料,那就必須利用 Synchronize 方法來避免不可預期的問題。而我的疑問在於,如果我只有產生一條 thread,可是這條 thread 和我的 process 本身有資源共享的話,還是需要把函式指標丟到 Synchronize 中嘛?如果要,那 process 沒有這個方法要怎麼辦?
然而自己測試一下,在 process 中產生一個 thread 並且在應用程式啟動就執行 thread: [code cpp] void __fastcall TForm1::FormCreate(TObject *Sender) { testThread = new TestThreadClass(false); } [/code] Thread 做的事情是把值累加,並且秀出來:( 其中 share 和 temp 為 Form 的 int ) [code cpp] void __fastcall TestThreadClass::Execute() { SetName(); Form1->Label1->Caption = "0"; //---- Place thread code here ---- while(!Terminated) { Sleep(300); Form1->temp = Form1->share 100; Form1->share = Form1->temp; Form1->Label1->Caption = Form1->Label1->Caption " " IntToStr(Form1->share); } } [/code] 最後在 Form 上面加上一個 Button,按一下的事件為: [code cpp] void __fastcall TForm1::Button2Click(TObject *Sender) { temp = share 5; share = temp; } [/code] 這樣做是在測試會不會發生, temp = share 5;,然後 thread 就搶去執行 temp = share 100;,使得值不正確,不過測試結果都沒發生不正確,不知道是實驗數據不夠多,還是說真的不會發生 race condition,還請板友解惑,感謝 編輯記錄
linly 重新編輯於 2008-01-24 09:55:46, 註解 無‧
|
本站聲明 |
1. 本論壇為無營利行為之開放平台,所有文章都是由網友自行張貼,如牽涉到法律糾紛一切與本站無關。 2. 假如網友發表之內容涉及侵權,而損及您的利益,請立即通知版主刪除。 3. 請勿批評中華民國元首及政府或批評各政黨,是藍是綠本站無權干涉,但這裡不是政治性論壇! |