[問題] class member function中使用std::thread
開發平台(Platform): (Ex: Win10, Linux, ...)
Linux
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
GCC
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
std::thread
問題(Question):
最近在實作multithread的時候遇到了一些問題
以下是程式碼,main function呼叫的函式會呼叫兩條thread幫忙做兩個加法運算
https://pastebin.com/GHn0WWmP
執行output結果是預期的37或73沒有問題
但當如果要呼叫thread的函式是class member function的時候就會compiler error
https://pastebin.com/E5vxyxXW
以下是我自己環境(GCC 4.8.5)的報錯
https://pastebin.com/nNem1nAv
我用線上編譯器onlinegdb.com試的error如下:
error: invalid use of non-static member function ‘void ATPG::test(int, int)’
稍微google一下有找到這篇類似問題的解法
https://thispointer.com/c11-start-thread-by-member-function-with-arguments/
但這篇的使用情境是在main function中開一條thread呼叫class member function
我的使用情境是class member function開thread呼叫其他class member function
用上述網站的解法一樣會有很多error
想請問前輩們這種使用情境下該怎麼呼叫thread比較正確
還是這其實是錯誤的使用方式,應該要在main function中開thread比較正確呢?
抱歉比較少multithread的coding經驗,麻煩前輩們賜教了,謝謝!
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 220.129.130.157 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1623189517.A.821.html
→
06/09 06:48,
2年前
, 1F
06/09 06:48, 1F
→
06/09 09:09,
2年前
, 2F
06/09 09:09, 2F
→
06/09 09:10,
2年前
, 3F
06/09 09:10, 3F
→
06/09 09:10,
2年前
, 4F
06/09 09:10, 4F
→
06/09 09:10,
2年前
, 5F
06/09 09:10, 5F
感謝兩位,仔細檢查後用那篇的方法重新再寫了一次沒有thread相關的error了
也謝謝c大的解釋,對為何要這樣用的原因也有比較了解了
--
但我在把要用thread呼叫的function改成static member之後又會遇到兩個問題
附上稍微複雜一點的code: https://pastebin.com/3pJVVmV4
1. 呼叫的function還有呼叫其他function(第32行),就會出現以下error
error: cannot call member function ‘void ATPG::tdf_pfFsim_all_fault(int,
int, int)’ without object
2. 呼叫的function如果有用到class data member(第29,30行)也會出現error
error: invalid use of member ‘ATPG::_piPattern’ in static member function
3. 如果class data member有在constructor初始化(第7行)也會出現error
error: ‘int ATPG::_faultCount’ is a static data member; it can only be
initialized at its definition
1.的部分把32行呼叫的function也改宣告成static可以解掉error
但這個function也會呼叫其他member function,要全部都宣告成static才不會有error
請問這是正確的解決方式嗎?還是有更好的解法
2.3.的部分我也是把data member改成static
但如果有在constructor初始化遇到的error我就不會解決了QQ
不知道有沒有更合適的解決方式,謝謝!
※ 編輯: skyHuan (220.129.130.157 臺灣), 06/09/2021 12:42:57
==
推
06/09 12:07,
2年前
, 6F
06/09 12:07, 6F
→
06/09 12:10,
2年前
, 7F
06/09 12:10, 7F
https://stackoverflow.com/questions/10998780/stdthread-calling-method-of-class
這篇的方法可以解決!也不會有上面static function的後續問題
感覺是比較適合的作法,感謝f大
==
→
06/09 13:45,
2年前
, 8F
06/09 13:45, 8F
→
06/09 13:46,
2年前
, 9F
06/09 13:46, 9F
→
06/09 13:58,
2年前
, 10F
06/09 13:58, 10F
C++確實沒有到非常熟,thread也是第一次使用
有試著自己搜尋跟除錯了,也有先理解並簡化問題才上來發問
可能因為比較趕還沒真的花很多時間仔細研究就上來發問
下次會自己多花時間多注意的,謝謝兩位前輩指教
※ 編輯: skyHuan (223.137.86.106 臺灣), 06/09/2021 16:37:08
→
06/09 22:00,
2年前
, 11F
06/09 22:00, 11F
→
06/09 22:00,
2年前
, 12F
06/09 22:00, 12F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章