【发布时间】:2019-03-12 11:48:02
【问题描述】:
我正在运行 x86,我想实际看到一个由我的机器上的无序执行引起的错误。我试过写一个,based off this wiki article,但我总是看到“x 的值为 33”:
#include<stdio.h>
#include<pthread.h>
#include <sys/types.h>
int x, f;
void *handler(void *ptr) {
while (f == 0);
// Expectation: Sometimes, this should print 11 due to out-of-order exec
printf("value of x is %d \n", x);
return NULL;
}
int main() {
pthread_t thread1;
while(1) {
x = 11; f = 0;
pthread_create(&thread1, NULL, handler, NULL);
x = 33;
f = 1;
pthread_join(thread1, NULL);
}
return 0;
}
可以说明乱序执行错误的最简单的 c 程序是什么?为什么有时这不打印“x 的值为 11”?
【问题讨论】:
-
线程启动不够快。只需在主函数中创建
sleep()后添加它即可获得您的 11 值 -
另一种方法是(也许)用一些 CPU 密集型进程加载系统以改变竞争条件
-
@Jean-FrançoisFabre 但
handler在f = 1;完成之前什么都不做,此时x = 33;已经完成。 -
@Jean-FrançoisFabre 不要认为这里有竞争条件。
-
@kiranBiradar 在放弃
while (f == 0);约束后,如果您多次运行该程序,也许迟早时间片调度会将pthread_create(&thread1, NULL, handler, NULL);与x = 33;分开并在其中运行handler破解,举报11。
标签: c multithreading x86 memory-barriers