gcc內置原子操做函數

    最近在用戶態下忽然須要用到原子變量,又不想本身編譯boost,思來索去,無心中竟發現gcc還有這一組內置函數.html

//原子操做,返回變化前的值
type __sync_fetch_and_add (type *ptr, type value);
type __sync_fetch_and_sub (type *ptr, type value);
type __sync_fetch_and_or (type *ptr, type value);
type __sync_fetch_and_and (type *ptr, type value);
type __sync_fetch_and_xor (type *ptr, type value);
type __sync_fetch_and_nand (type *ptr, type value);

//原子操做,返回變化後的值
type __sync_add_and_fetch (type *ptr, type value);
type __sync_sub_and_fetch (type *ptr, type value);
type __sync_or_and_fetch (type *ptr, type value);
type __sync_and_and_fetch (type *ptr, type value);
type __sync_xor_and_fetch (type *ptr, type value);
type __sync_nand_and_fetch (type *ptr, type value);

按照官方文檔的說法,ide

GCC will allow any integral scalar or pointer type that is 1, 2, 4, or 8 bytes in length. 16-byte integral types are also allowed if `__int128' (see __int128) is supported by the architecture.函數

也就是說至少支持長度爲 1,2,4,8的整形。16位是否支持取決於體系結構測試


簡單的測試了一下,發現不用include任何頭文件,gcc編譯時會自動替換成對應的彙編代碼。fetch

int main()
{
    int a = 100;
    __sync_fetch_and_add(&a,1);
    return a;
}

看了下生成的彙編是這樣的:ui

    .file   "funtest.c"
    .text
    .globl  main
    .type   main, @function
main:
.LFB0:
    .cfi_startproc
    pushq   %rbp
    .cfi_def_cfa_offset 16
    .cfi_offset 6, -16 
    movq    %rsp, %rbp
    .cfi_def_cfa_register 6
    movl    $100, -4(%rbp)
    lock addl   $1, -4(%rbp)                //__sync_fetch_and_add(&a,1);對應的指令
    movl    -4(%rbp), %eax
    popq    %rbp
    .cfi_def_cfa 7, 8
    ret 
    .cfi_endproc
.LFE0:
    .size   main, .-main
    .ident  "GCC: (Debian 4.7.2-5) 4.7.2"
    .section    .note.GNU-stack,"",@progbits


參考連接atom

https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/_005f_005fatomic-Builtins.html#_005f_005fatomic-Builtinsspa

相關文章
相關標籤/搜索