- 论坛徽章:
- 0
|
这个程序哪位在SMP LINUX机器上帮运行一下。
gcc -lpthread atomic.c -o testa
./testa 没有参数就是用原子复制
./testa X 有任何参数就是故意不用原子复制
如果不是原子的,程序会退出,否则一直跑。还可以观察到count被其它THREAD改了的情况
- # include <stdio.h>
- # include <stdlib.h>
- # include <pthread.h>
- # include <unistd.h>
- int not_atomic = 0;
- int runFlag = 1;
- int count = 0;
- void *testa( int id );
- int main( int argc, char **argv )
- {
- pthread_t thread;
- int i, ret;
- if(argc > 1 && argv[0][0]) not_atomic = 1;
- for( i = 0; i < 8; i++ ){
- ret = pthread_create( &thread, NULL, (void *(*)(void *))testa, (void *)i );
- if ( ret != 0 ){
- perror( "pthread_create" );
- exit(-1);
- }
- }
- while(runFlag) sleep(5);
- return 0;
- }
- void *testa( int id )
- {
- int i;
- unsigned int k, v;
- k = 0x11111111*id;
- while(runFlag){
- for( i=0; i<10000; i++ ){
- if(not_atomic == 0) {
- count = k;
- } else {
- ((short*)&count)[0] = ((short*)&k)[0];
- ((short*)&count)[1] = ((short*)&k)[1];
- }
- if(count != k)
- printf("%08x %08x\n", k, count);
- v = count;
- if((v & 0x0000ffff) != (v >> 16)) {
- printf("NOT ATOMIC VALUE FOUND: %p %p\n", v, count);
- runFlag = 0;
- }
- }
- }
- return NULL;
- }
复制代码 |
|