日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

linux无锁化编程

發布時間:2025/6/15 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux无锁化编程 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

? ? ? ? ?muduo庫中使用了幾個linux無鎖編程接口,這些函數在多線程下操作時無需加鎖也能實現原子操作,而且加鎖會影響性能。
__sync_val_compare_and_swap(type *ptr, type oldval, ?type newval, ...) ? 如果*ptr == oldval,就將newval寫入*ptr
__sync_fetch_and_add( &global_int, 1) ? 先fetch(獲得),然后自加,返回的是自加以前的值
__sync_lock_test_and_set(type *ptr, type value, ...) ? ?將*ptr設為value并返回*ptr操作之前的值

#include <stdio.h> #include <pthread.h> #include <unistd.h>int sum = 0;/*void* adder1(void *p) {for(int i = 0; i < 1000000; i++) // 百萬次{sum++;}return NULL; }*//*void* adder2(void *p) {int old = sum;for(int i = 0; i < 1000000; i++) // 百萬次{while(!__sync_bool_compare_and_swap(&sum, old, old + 1)) // 如果old等于sum, 就把old+1寫入sum{old = sum; // 更新old}}return NULL; }*/void* adder3(void *p) {for(int i = 0; i < 1000000; i++) // 百萬次{__sync_fetch_and_add(&sum,1); }return NULL; }int main() {pthread_t threads[10];for(int i = 0;i < 10; i++){pthread_create(&threads[i], NULL, adder3, NULL);}for(int i = 0; i < 10; i++){pthread_join(threads[i], NULL);}printf("sum is %d\n",sum);return 0; }

addr1結果不是我們預期的,addr2和addr3是我們預期的(10000000),編譯要加上選項-lpthread -march=nocona -mtune=generic

?

參考地址:https://blog.csdn.net/stpeace/article/details/81150393

? ? ? ? ? ? ? ? ? https://blog.csdn.net/hzhsan/article/details/25124901

總結

以上是生活随笔為你收集整理的linux无锁化编程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。