Last active
October 16, 2017 01:57
-
-
Save bachue/b57fefcfdb2f40cf1f905b1e9ed08afb to your computer and use it in GitHub Desktop.
根据 http://blog.shengbin.me/posts/gcc-attribute-aligned-and-packed ,写了个测试用例,执行在 x86_64 上。理论上应该输出 80000 才对,实际执行的时候只有在 gcc 使用 -O1 及其以上优化时,才能成功。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <time.h> | |
#include <string.h> | |
#include <pthread.h> | |
void *add_counter(void* c) { | |
int i; | |
for (i = 0; i < 10000; i++) { | |
(*(int*)c)++; | |
} | |
return NULL; | |
} | |
int main() { | |
const int ThreadN = 8; | |
int i, ret; | |
pthread_t threads[ThreadN]; | |
unsigned long counter __attribute__ ((aligned (64))) = 0UL; | |
for (i = 0; i < ThreadN; i++) { | |
if ((ret = pthread_create(&threads[i], NULL, add_counter, (void*)(&counter))) != 0) { | |
fprintf(stderr, "error: %s", strerror(ret)); | |
return 1; | |
} | |
} | |
for (i = 0; i < ThreadN; i++) { | |
if ((ret = pthread_join(threads[i], NULL)) != 0) { | |
fprintf(stderr, "error: %s", strerror(ret)); | |
return 1; | |
} | |
} | |
printf("counter: %lu\n", counter); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment