我有一個 structure 

struct data_
{
    volatile char c ;
    volatile char b ;
} ;


typedef struct data_ data ;

 

Thread1 :

data.c = 1 ;

Thread2:

data.b = 1 ;

Main :

    for(idx=0;idx<1000000;idx++)
    {
        icnt = 0 ; dx.c=0 ; dx.b=0 ;
        sem_post(sem1) ;
        sem_post(sem2) ;
        sem_wait(sem3) ;
        if( ! ((dx.c==1)&&(dx.b==1))  )
        {
            printf("result that (c==%d && b==%d) \n",dx.c,dx.b) ;
            ++iflag1 ;
        }else{
            ++iflag2 ;
        }
    } //for

很明顯 ,  這個 test X==1 && y==1 每次都成立 !!!!

 

修改 :

struct data_
{
    unsigned char c:4 ;
    unsigned char b:4 ;
} ;

typedef struct data_ data ;

也就是說 ,  bit-field c and b 各有 4 bits !!  此時再測試 , 就會有 ! ( (x==1)&&(y==1))  的存在 !!!!

原因是 , char b , char c 可以做 atomic operation , 4 bits 的 c and b 不行 !! 根據文件 ,

unsigned char c:4 以及 unsigned char b:4  這兩個欄位在同一個 memory location !!!

一個 int 有 32 bits , 其連續的 unsigned int x: 3; unsigned int y:10; unsigned int z:5;

這些都是同一個  memory location , 還會捕成 32 bits 滿滿 !!  相同 的 memory location 變數 ,

會互相蓋來蓋去 ,  這個 test 重點是 memory location , 以及 concurrency !!!

 

struct { char c ;char b}  <=  c and b 不同 memory location , 所以不會干擾彼此 !!

struct { int  c ;int  b}  <=  c and b 不同 memory location , 所以不會干擾彼此 !!

struct { char c :4;char b:4}  <=  c and b 相同 memory location , 所以會干擾彼此 !!

 

 

 

arrow
arrow
    全站熱搜

    hedgezzz 發表在 痞客邦 留言(0) 人氣()