10.并发下锁操作及原子操作

图解#

代码#

#define _GNU_SOURCE  // 启用GNU扩展以包含自旋锁定义
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>



#define THREAD_COUNT     10

pthread_mutex_t mutex;
pthread_spinlock_t spinlock;


int inc(int *value, int add) {
    int old;

    __asm__ volatile(
        "lock; xaddl %2, %1;"
        : "=a" (old)
        : "m" (*value), "a"(add)
        : "cc", "memory"
    );

    return old;
}



void *thread_callback(void *arg) {

    int *pcount = (int*) arg;
    int i = 0;
    while (i++ < 100000) {
#if 0
        (*pcount)++;
#elif 0
        pthread_mutex_lock(&mutex);
        (*pcount)++;
        pthread_mutex_unlock(&mutex);
#elif 0
        pthread_spin_lock(&spinlock);
        (*pcount)++;
        pthread_spin_unlock(&spinlock);
#else
        inc(pcount, 1);
#endif
        usleep(1);
    }
    
}




int main() {

    pthread_t threadid[THREAD_COUNT] = {0};

    pthread_mutex_init(&mutex, NULL);
    pthread_spin_init(&spinlock, PTHREAD_PROCESS_SHARED);

    int i = 0;
    int count = 0;
    for (i = 0; i < THREAD_COUNT; i++) {
        pthread_create(&threadid[i], NULL, thread_callback, &count);
    }

    for (i = 0; i < 100; i++) {
        printf("count : %d\n", count);
        sleep(1);
    }

}

编译#

gcc -o lock lock.c -lpthread

作者:lotuslaw

出处:https://www.cnblogs.com/lotuslaw/p/18705787

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted @   lotuslaw  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
历史上的今天:
2023-02-09 15-批次之间具有堆叠的LSTM
2023-02-09 14-LSTM多步预测-多步预测的LSTM网络
2023-02-09 13-LSTM多步预测-静态模型预测
2023-02-09 12-LSTM多变量-定义&训练模型
2023-02-09 11-LSTM多变量-LSTM数据预处理_tmp
2023-02-09 10-LSTM多变量-LSTM数据预处理
more_horiz
keyboard_arrow_up light_mode palette
选择主题
menu
点击右上角即可分享
微信分享提示