CPU 乱序执行验证
生活随笔
收集整理的這篇文章主要介紹了
CPU 乱序执行验证
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
受到一個(gè)問題啟發(fā):linux kernel 為什么加 smp_mb,怎么引起的,添加又有怎么解決的問題?
最近遇到CPU的亂序問題,總是理論性的東西和討論,找了個(gè)時(shí)間寫了測(cè)試程序,驗(yàn)證CPU亂序執(zhí)行的存在,理論知識(shí)網(wǎng)上已經(jīng)很多,不再啰嗦,理論加實(shí)踐,才能理解的更加深刻
/*this program test CPU out of order execute.ENV: CPU need more than two core threadgcc -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 stoppthread_join(pit1, NULL);pthread_join(pit2, NULL);// we don't think, but ...if (x == 0 && y == 0)printf("i = %d\n", i);} }執(zhí)行結(jié)果如下,會(huì)時(shí)不時(shí)出現(xiàn) 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 .....?
總結(jié)
以上是生活随笔為你收集整理的CPU 乱序执行验证的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 给年份year,定义一个宏,以判别该年份
- 下一篇: python逻辑回归代码_Logisti