- 最後登錄
- 2024-4-29
- 在線時間
- 0 小時
- 註冊時間
- 2013-1-24
- 閱讀權限
- 20
- 精華
- 0
- UID
- 12541808
- 帖子
- 1051
- 積分
- 617 點
- 潛水值
- 27330 米
| 如果你忘記伊莉的密碼,請在登入時按右邊出現的 '找回密碼'。輸入相關資料後送出,系統就會把密碼寄到你的E-Mail。 本帖最後由 cockroachrun 於 2018-7-30 04:46 PM 編輯
MY0613 發表於 2018-7-26 04:26 PM
結果:
這程式有bug
bug 發生在這段code- while ((tb + ThreadIndex)->IsIdle == false) // 看現在哪個執行緒是空的
- {
- if (ThreadIndex < _ThreadNum )
- ThreadIndex++;
- else
- ThreadIndex = 0;
- Sleep(100);
- }
複製代碼 這段code 會讓你的ThreadIndex 為 8 . 由你的結果也發現確實會出現8
當是8 時 (tb+ThreadIndex)->ThreadIndex = ... 就會破壞記億體. 讓程式當掉
以上說的不是重點.
板大的問題. 為什麼傳給thread 的function . 如是class 的function. 必需是static 的.
因為_beginthreadex() 給的thread entry function 必須是傳統的c function.
class 的member function(非static function). 並不是.
I.
class 的非 static member function .雖然你寫這 void F(int) 只有一個int 參數. 但是compiler 會自動幫你加入一個參數. 這個參數你可以想成就是 this .
所以 你的一個 class instance a 去叫用 F(100) 寫成 a.F(100) compiler 回傳給F() 兩個東西. 一個是100, 另一個是 &a . 您可以在F() 當中 用this 去取得.
II.
對於class 的static member function . compiler 不會傳送額外的參數. 叫用方法就跟傳統c 一樣. static member function 當中. 也沒有this 可以使用.
由上訴的I , II 點. 就可以明白. 為什麼要用static member function . 當作是_beginthreadex() 的entry function
板大的另一個問題. 是針對M 大的回應程式當中 :
- 但我試過沒有(tb + nowThread)->_wrap = (void*) this;好像也可以,為什麼?
複製代碼 當你把這行去掉為什麼也能跑. 也能得到正確的資料.
很簡單 因為 void TestWrapperMultThreadToClass::Test (ThreadBlockParam* _tb )
Test function 內沒有存取任何一個 class member data. 它須要的資料不是從 _tb 得到. 不然就是自己產生. 所以不會產生 記憶體存取錯誤.
拿掉 (tb + nowThread)->_wrap = (void*) this; 這並不是一個好的寫法. 因為M大的程式 FunctionCalledByThread() 中有用到TestWrapperMultThreadToClass *_this = (_tb->_wrap);
然後呼叫了 _this->Test(_tb) 如沒有寫(tb + nowThread)->_wrap = (void*) this; 那這時的_this 並不是一個合法的值. C++ 的runtime 不會去檢查這個值是否是正確的. 直接把他傳給Test(). 在這個Test() function 中如上面說的沒有去存取class member data. 所以不會出問題. 但某一天. 你改了Test() 去存取class 的member data 時. 就會發生錯誤 . 然後呢.. 你會debug 了了辦天也找不到問題.
... |
|