【发布时间】:2018-03-14 13:23:58
【问题描述】:
我们被要求创建 4 个线程,每个线程增加(SPIN/4 倍)全局变量 compteur 的值,以理应注意到每个线程在另一个线程完成迭代之前正在访问/更改全局变量(即为什么SPIN 被赋予了一个非常大的数字),例如线程号 1 首先访问 compteur,而它正在增加另一个线程访问 compteur 并看到 compteur = 0 仍然,最后得出结论,我们必须使用 MUTEX。
问题是程序总是在不应该的时候给我与 SPIN 相同的值。
你能解释一下为什么吗?
#define SPIN 40000000
int compteur = 0;
void *routine_thread(void *arg) {
int i;
printf("accessing thread ... \n");
for (i = 0; i < SPIN / 4; ++i) {
compteur++;
}
printf("quitting thread ... \n");
pthread_exit(NULL);
}
int main(int argc, char *argv[]) {
pthread_t thread_id[4];
void *resultat_thread;
int statut;
int i;
for (i = 0; i < 4; i++) {
statut = pthread_create(&thread_id[i], NULL, routine_thread, NULL);
if (statut != 0) {
fprintf(stderr, "error creating thread\n");
exit(EXIT_FAILURE);
}
statut = pthread_join(thread_id[i], &resultat_thread);
if (statut != 0) {
fprintf(stderr, "error joining the thread\n");
exit(EXIT_FAILURE);
}
}
printf("compteur value is : %d\n", compteur);
if (resultat_thread == NULL)
return EXIT_FAILURE;
else
return EXIT_SUCCESS;
}
【问题讨论】:
-
你一次只运行一个线程...
-
好的,知道了,谢谢
-
附带说明:您不能通过测试来证明程序没有竞争条件。一些竞争条件很少会导致问题,以至于测试很可能会错过它们。而且,即使您愿意接受由竞争条件引起的少量崩溃/错误;如果您在自己的计算机上进行测试,您无法证明在客户计算机上的费率是可以接受的低水平。
标签: c multithreading pthreads global mutex