[問題] pthread 的 race condition

看板C_and_CPP作者時間16年前 (2009/10/28 18:41), 編輯推噓2(2010)
留言12則, 7人參與, 最新討論串1/1
( *[1m *[m 為色碼,可以按 Ctrl+V 預覽會顯示的顏色 ) ( 未必需要依照此格式,文章條理清楚即可 ) 遇到的問題: (題意請描述清楚) 在Linux底下希望能寫個有 race condition 的範例程式 但是程式怎麼跑都是正確的結果 想請問為什麼跑不出 race condition 的情形 開發平台: Ubuntu 9.04 desktop 有問題的code: #include <stdio.h> #include <pthread.h> #define NTHREADS 100 void *thread_function(void *); int counter = 0; int main() { pthread_t thread_id[NTHREADS]; int i, j; for (i = 0; i < NTHREADS; i++) { pthread_create(&thread_id[i], NULL, thread_function, NULL); } for (j = 0; j < NTHREADS; j++) { pthread_join(thread_id[j], NULL); } /* Now that all threads are complete I can print the final result. */ /* Without the join I could be printing a value before all the threads */ /* have been completed. */ printf("Final counter value: %d\n", counter); } void *thread_function(void *dummyPtr) { printf("Thread number %ld\n", pthread_self()); counter++; } 補充說明: -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.120.38.78

10/28 18:48, , 1F
不好意思想閒聊一個東西...UBUNTU 9.10出嚕嗎?@"@
10/28 18:48, 1F

10/28 18:55, , 2F
你跑出怎樣的結果?你覺得應該會跑出怎樣的結果?為什麼?
10/28 18:55, 2F

10/28 20:32, , 3F
如果只是希望他沒有交錯出現的話,那應該不叫race...
10/28 20:32, 3F

10/28 21:21, , 4F
應該是希望看到counter的值小於100
10/28 21:21, 4F

10/28 22:27, , 5F
試試 int t = counter; 印過 thread id 之後再 counter=t+1;
10/28 22:27, 5F

10/28 22:28, , 6F
為什麼單用 counter++; 不行... 我也不知道 囧
10/28 22:28, 6F

10/29 00:17, , 7F
試過加t 還是不行啊 QQ
10/29 00:17, 7F

10/29 00:53, , 8F
因為cpu太快
10/29 00:53, 8F

10/29 00:54, , 9F
記得在某個地方加上 sleep(1) 之類的好像就可以錯開
10/29 00:54, 9F

10/29 11:07, , 10F
counter++的地方,用迥圈做100次,然後看最後印出的值,
10/29 11:07, 10F

10/29 11:08, , 11F
如果,最後的值不是10000,那就是race condition
10/29 11:08, 11F

10/29 12:09, , 12F
試過用迴圈跑1000次counter++ 還是沒有race condition
10/29 12:09, 12F
文章代碼(AID): #1Aw1_O3O (C_and_CPP)