DO
#include <func.h>
void* start_routine(void* args) {
long* value = (long*) args;
for(long i = 0; i < 100000000; i++) {
(*value)++; // 对共享数据的操作
// 为什么结果不正确:++操作不是原子性的
// 为什么每次结果都不一样:调度是不确定的
// 每次运行时线程的调度顺序和时间片分配不同,
// 导致数据竞争的情况也不同
}
}
int main(int argc, char* argv[])
{
long* value = (long*)calloc(1, sizeof(long)); // *value = 0
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, start_routine, value);
pthread_create(&tid2, NULL, start_routine, value);
// 主线程等待两个子线程结束
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
printf("value = %ld\n", *value);
return 0;
}