|
发表于 2009-12-3 14:50:43
|
显示全部楼层
Post by platinum;2052015
我的测试发现,用 __asm__ __volatile__ ("":::"memory"); 替换 printf,结果是正确的
完整代码如下
- #include <stdio.h>
- #include <linux/types.h>
- #define UNIT_BITS 32
- struct data {
- __u32 d3;
- __u32 d2;
- __u32 d1;
- __u32 d0;
- };
- static inline void
- data_set_hard (struct data *ret,
- __u32 a, __u32 b, __u32 c, __u32 d)
- {
- ret->d3 = a;
- ret->d2 = b;
- ret->d1 = c;
- ret->d0 = d;
- }
- static inline void
- data_set (struct data *ret, int bit)
- {
- __u32 *data[4];
- int a, b;
- a = bit / UNIT_BITS;
- b = bit % UNIT_BITS;
- data[0] = &ret->d0;
- data[1] = &ret->d1;
- data[2] = &ret->d2;
- data[3] = &ret->d3;
- *data[a] |= 1 << b;
- __asm__ __volatile__ ("":::"memory");
- }
- int
- main (void)
- {
- struct data test = {0};
- int i;
- data_set_hard(&test, 0, 0, 0, 0);
- for (i=0; i<UNIT_BITS*4; i++) {
- data_set(&test, i);
- }
- printf ("test = %.8x, %.8x, %.8x, %.8x\n",
- test.d3, test.d2, test.d1, test.d0);
- return 0;
- }
复制代码
# gcc -O2 -Wall -o test test.c
# ./test
test = ffffffff, ffffffff, ffffffff, ffffffff
# gcc -v
使用内建 specs。
目标:i686-pc-linux-gnu
配置为:/var/tmp/portage/sys-devel/gcc-4.3.4/work/gcc-4.3.4/configure --prefix=/usr --bindir=/usr/i686-pc-linux-gnu/gcc-bin/4.3.4 --includedir=/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include --datadir=/usr/share/gcc-data/i686-pc-linux-gnu/4.3.4 --mandir=/usr/share/gcc-data/i686-pc-linux-gnu/4.3.4/man --infodir=/usr/share/gcc-data/i686-pc-linux-gnu/4.3.4/info --with-gxx-include-dir=/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4 --host=i686-pc-linux-gnu --build=i686-pc-linux-gnu --disable-altivec --disable-fixed-point --enable-nls --without-included-gettext --with-system-zlib --disable-checking --disable-werror --enable-secureplt --disable-multilib --enable-libmudflap --disable-libssp --enable-libgomp --disable-libgcj --with-arch=i686 --enable-languages=c,c++,treelang,fortran --enable-shared --enable-threads=posix --enable-__cxa_atexit --enable-clocale=gnu --with-bugurl=http://bugs.gentoo.org/ --with-pkgversion='Gentoo 4.3.4 p1.0, pie-10.1.5'
线程模型:posix
gcc 版本 4.3.4 (Gentoo 4.3.4 p1.0, pie-10.1.5)
囧……偶又米有说清楚……
我前面说的都是基于最开始的代码的,我第一次说加一行asm,我是加在了
for (...)
{
data_set...
__asm__ ....
}
后来我说其实可以放在printf前面,我的意思其实是
for (...)
{
data_set...
}
__asm__...
printf(...)
我的本意是想让最后这个输出结果的printf强制从内存取值(因为我发现前面的循环的代码是没问题的,只是最后输出的结果是不对的),但是我发现不行,因为像上文说的,似乎data_set_hard被放在后面了,所以还是结果不对 |
|