linux編程的108種奇淫巧計-1(FALSE SHARING)

來源:互聯網
上載者:User

        我打算開個長篇系列部落格,預計108篇吧,但願能在1-2年內完成。

 

        註:考慮到我本人長期使用linux系統做開發,因此有些代碼在windows環境下無法編譯或者會有問題,建議大家都使用linux環境做實驗,最好是2.6核心的,處理器需要是多核。很多讀者說我是紙上談兵,這個確實不好,從本系列開始基本都是50行左右的代碼。本系列不代表任何學術或業界立場,僅我個人興趣愛好,由於水平有限,錯誤難免,請不要有過分期望。

 

        廢話不多說,今天就寫第一篇如下:

 

        以下一段代碼分別編譯成兩個程式,僅僅是變數定義的差別,執行時間差距巨大,這是什麼原因呢?

        本部落格暫不解密,等數天后,我把後半部寫上,希望讀者朋友們踴躍實驗,並回答。

 

#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <stdlib.h>
#ifdef FS
size_t cnt_1;
size_t cnt_2;
#endif
#ifdef NONFS

size_t __attribute__((aligned(64))) cnt_1;
size_t __attribute__((aligned(64))) cnt_2;
#endif
void* sum1(void*)
{
        for(int i=0;i < 10000000;++i) {
                cnt_1 += 1;
        }
};
void* sum2(void*)
{
        for(int i=0;i < 10000000;++i) {
                cnt_2 += 1;
        }
};
int main()
{
        pthread_t* thread = (pthread_t*) malloc(2*sizeof( pthread_t));
        pthread_create(&thread[0],NULL,sum1,NULL);  //建立2個線程分別求和
        pthread_create(&thread[1],NULL,sum2,NULL);
        pthread_join(thread[0],NULL);    //等待2個線程結束計算。
        pthread_join(thread[1],NULL);
        free(thread);
        printf("cnt_1:%d,cnt_2:%d",cnt_1,cnt_2);
}
 編譯方法:
g++ fs.cpp -o test_nfs -g -D NONFS –lpthread
g++ fs.cpp -o test_fs -g -D FS –lpthread

用time ./test_nfs 和 time ./test_fs會發現執行時間差別很大,請讀者踴躍跟帖作答,謝謝。

 

續篇參見:http://blog.csdn.net/pennyliang/archive/2010/10/26/5966433.aspx

 

 

網友linyai做了實驗,大家可以參考一下,以下來自跟帖。

 

 

linyai 發表於Thu Oct 21 2010 10:11:22 GMT+0800 (China Standard Time)  舉報回複刪除
fs: 0m0.083s nfs: 0m0.043s fs: 0m0.130s nfs: 0m0.034s fs: 0m0.084s nfs: 0m0.037s fs: 0m0.086s nfs: 0m0.042s

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.