受到一个问题启发:linux kernel 为什么加 smp_mb,怎么引起的,添加又有怎么解决的问题?
最近遇到CPU的乱序问题,总是理论性的东西和讨论,找了个时间写了测试程序,验证CPU乱序执行的存在,理论知识网上已经很多,不再啰嗦,理论加实践,才能理解的更加深刻
/*
this program test CPU out of order execute.
ENV: CPU need more than two core thread
gcc -Wall -O3 out_of_order.c -o out_of_order -lpthread
*/
#include <stdio.h>
#include <pthread.h>
static long a = 0, b = 0;
static long x = 0, y = 0;
#define mb() __asm__ __volatile__("mfence":::"memory")
#define rmb() __asm__ __volatile__("lfence":::"memory")
#define wmb() __asm__ __volatile__("sfence":::"memory")
#define barrier() __asm__ __volatile__("": : :"memory")
void* func1(void *arg)
{
a = 1;
barrier();
// mb();
x = b;
return NULL;
}
void* func2(void *arg)
{
b = 1;
barrier();
// mb();
y = a;
return NULL;
}
int main()
{
int i = 0;
pthread_t pit1, pit2;
while (1) {
i++;
a = 0; b = 0;
x = 0; y = 0;
pthread_create(&pit1, NULL, &func1, NULL);
pthread_create(&pit2, NULL, &func2, NULL);
// wait for pthread stop
pthread_join(pit1, NULL);
pthread_join(pit2, NULL);
// we don't think, but ...
if (x == 0 && y == 0)
printf("i = %d\n", i);
}
}
执行结果如下,会时不时出现 x==0 && y == 0的情况
i = 20
i = 24
i = 26
i = 28
i = 31
i = 34
i = 38
i = 42
i = 43
i = 45
i = 47
i = 49
i = 51
i = 53
i = 57
i = 59
i = 63
i = 71
.....