我写了一个多线程程序来演示英特尔处理器的乱序效果。该程序附在本文末尾。预期的结果应该是当 x 被 handler1 打印为 42 或 0 时。但是,实际结果始终为 42,这意味着不会发生乱序效应。
我使用命令“gcc -pthread -O0 out-of-order-test.c”编译了程序我在英特尔 IvyBridge 处理器英特尔(R ) Xeon(R) CPU E5-1650 v2。
有谁知道我应该怎么做才能看到乱序效应?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int f = 0, x = 0;
void* handler1(void *data)
{
while (f == 0);
// Memory fence required here
printf("%d\n", x);
}
void* handler2(void *data)
{
x = 42;
// Memory fence required here
f = 1;
}
int main(int argc, char argv[])
{
pthread_t tid1, tid2;
pthread_create(&tid1, NULL, handler1, NULL);
pthread_create(&tid2, NULL, handler2, NULL);
sleep(1);
return 0;
}