查看完整版本: (已解決)有關pthread
頁: [1]

acow10109 發表於 2016-11-30 10:08 PM

(已解決)有關pthread

本帖最後由 acow10109 於 2016-12-1 01:16 PM 編輯

我想請問當在for迴圈時運行pthread時為何會出現以下情況
程式碼

https://gist.github.com/anonymous/f64d09695f78375fa3559ba31fb40965

結果如下 為何在pthread下是3 2 1 0這樣倒回去呢? 如果要跟上面那個for迴圈一樣 該如何改比較好 請各位大大指點(linux環境下執行)http://www02.eyny.com/forum.php?mod=image&aid=116752846&size=300x300&key=6b6bc17774be5384641a2b97edfbded9&nocache=yes&type=fixnone
...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div><div></div>

scottcheng 發表於 2016-12-1 01:47 AM

thread 本來跟被分配的 core 有關, 妳沒辦法保證哪一個會被先跑
妳可以試試看用 pthread_attr_setschedpolicy  設 thread 為  SCHED_FIFO 去試看看
pthread_attr 是 pthread_create 第二個參數. ..

最傻的方法, 就是在pthread_create 每一次loop加各 sleep 大概一定會依照你順序.

還有很多耍白的方法. 例如用 pthread_cond  去一個一個等..這樣夠蠢了吧

不用太在意thread 順序, 除非你一定要某動了, 下一個才能動.. 那就用cond

例如說兩個thread , 其中一個要等另外一個 data ready..妳也可以一直polling 也可以用cond..一直polling 壞處是, 如果loop沒經過甚麼code...妳的cpu loading..就超嗨了
...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div>

acow10109 發表於 2016-12-1 07:48 AM

scottcheng 發表於 2016-12-1 01:47 AM static/image/common/back.gif
thread 本來跟被分配的 core 有關, 妳沒辦法保證哪一個會被先跑
妳可以試試看用 pthread_attr_setschedpoli ...

大概了解了 另外我想加問一個問題
當我的for迴圈用下面的形式時,為何&id帶入的值都是4


https://gist.github.com/anonymous/7410127b61c583cd69bd8c3046bb6c1e

...<div class='locked'><em>瀏覽完整內容,請先 <a href='member.php?mod=register'>註冊</a> 或 <a href='javascript:;' onclick="lsSubmit()">登入會員</a></em></div>

scottcheng 發表於 2016-12-1 12:04 PM

for 迴圈裡面的變數, 只有 for 裡面才有用, 所以當離開 for 時, id 就無效化, 當時id所使用的address, 假使還沒被破壞, 就是離開 for 的最後 ++ 為 4

因此四個 thread 都是參考到同一個位址, 當然會都是4

acow10109 發表於 2016-12-1 01:15 PM

scottcheng 發表於 2016-12-1 12:04 PM static/image/common/back.gif
for 迴圈裡面的變數, 只有 for 裡面才有用, 所以當離開 for 時, id 就無效化, 當時id所使用的address, 假使 ...

謝謝 我瞭解了 感謝大大的解答<br><br><br><br><br><div></div>
頁: [1]