[問題] pthread 的 race condition
( *[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
10/28 18:48, 1F
→
10/28 18:55, , 2F
10/28 18:55, 2F
→
10/28 20:32, , 3F
10/28 20:32, 3F
→
10/28 21:21, , 4F
10/28 21:21, 4F
推
10/28 22:27, , 5F
10/28 22:27, 5F
→
10/28 22:28, , 6F
10/28 22:28, 6F
→
10/29 00:17, , 7F
10/29 00:17, 7F
→
10/29 00:53, , 8F
10/29 00:53, 8F
→
10/29 00:54, , 9F
10/29 00:54, 9F
推
10/29 11:07, , 10F
10/29 11:07, 10F
→
10/29 11:08, , 11F
10/29 11:08, 11F
→
10/29 12:09, , 12F
10/29 12:09, 12F