http://stackoverflow.com/questions/20113375/implement-double-word-cas-by-assambly

 

struct ptr_
{
   
uint64_t pointer;
   
uint64_t serial;
} __attribute__ (( __aligned__(16)));
typedefstruct ptr_ nodeptr ;

 

inlinestaticbool
cas_64_2
(nodeptr *original,nodeptr *expected,nodeptr *newone)
{
   
uint64_t*target ;
   
uint64_t*compare;
   
uint64_t*set;

    target
=(uint64_t*) original ;
    compare
=(uint64_t*) expected ;
   
set=(uint64_t*) newone ;
   
bool z;

    __asm__ __volatile__
("movq 0(%4), %%rax;"
                        
"movq 8(%4), %%rdx;"
                        
"lock;""cmpxchg16b %0; setz %1"
                           
:"+m"(*target),
                             
"=q"(z)
                           
:"b"  (set[0]),
                             
"c"  (set[1]),
                             
"q"  (compare)
                           
:"memory","cc","%rax","%rdx");


   
return z;
}

 

inlinestaticbool
cas_64_2
(nodeptr *original,nodeptr *expected,nodeptr *newone)
{
   
uint64_t*target ;
   
uint64_t*compare;
   
uint64_t*set;

    target
=(uint64_t*) original ;
    compare
=(uint64_t*) expected ;
   
set=(uint64_t*) newone ;
   
bool z;


    __asm__ __volatile__
(
       
"lock cmpxchg16b %1\n\t"
       
"setz %0\n"
       
:"=q"(z)
       
,"+m"(*target )
       
:"a"( expected->pointer ),"d"(expected->serial )
       
,"b"( newone->pointer ),"c"( newone->serial )
       
:"cc"
   
);

   
return z;
}

 

第二個方法 , stackorverflow 說會比較好  !!!

int main()
{
    char *s,*s2 ;
    s  = (char*) malloc(100) ;
    s2 = (char*) malloc(100) ;
    strcpy(s,"hello world!!\n") ;
    strcpy(s2,"s2 string here !!!!!!\n") ;

    nodeptr *nodeptr1,*nodeptr2,*nodeptr3 ;

    nodeptr1 = (nodeptr *) malloc(sizeof(nodeptr)) ;
    nodeptr1->pointer = (uint64_t) s ;
    nodeptr1->serial  = 1 ;
    nodeptr2->pointer = (uint64_t) s ;
    nodeptr2->serial  = 0 ;

    nodeptr3 = (nodeptr *) malloc(sizeof(nodeptr)) ;
    nodeptr3->pointer = (uint64_t) s2 ;
    nodeptr3->serial  = 10000 ;

    if(cas_64_2(nodeptr1,nodeptr2,nodeptr3))
    {
        printf("cas true \n") ;
        printf("nodeptr1->pointer=(%s),nodeptr1->serial=(%d) \n",
        (char*)nodeptr1->pointer,nodeptr1->serial) ;
    }
    else
    {
        printf("cas false \n") ;
    }
}

 

創作者介紹
創作者 hedgezzz 的頭像
hedgezzz

hedgezzz的部落格

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