Linux基础 - Linux ARM 原子读写

发布时间:2023年12月22日

背景

在Linux Arm kernel实现原子读写64位数据;

接口代码

#include <linux/atomic.h>
atomic64_t my_atomic_var = ATOMIC64_INIT(0);

void atomic_write_64(atomic64_t *v, int64_t new_value) {
    atomic64_set(v, new_value);
}

int64_t atomic_read_64(atomic64_t *v) {
    return atomic64_read(v);
}

使用自旋锁

#include <linux/spinlock.h>

spinlock_t my_lock = SPIN_LOCK_UNLOCKED;
uint64_t my_shared_var = 0;

void write_64(uint64_t new_value) {
    spin_lock(&my_lock);
    my_shared_var = new_value;
    spin_unlock(&my_lock);
}

uint64_t read_64(void) {
    uint64_t value;
    spin_lock(&my_lock);
    value = my_shared_var;
    spin_unlock(&my_lock);
    return value;
}

使用读写锁

#include <linux/rwlock.h>

rwlock_t my_rwlock = RW_LOCK_UNLOCKED;
uint64_t my_shared_var = 0;

void write_64(uint64_t new_value) {
    write_lock(&my_rwlock);
    my_shared_var = new_value;
    write_unlock(&my_rwlock);
}

uint64_t read_64(void) {
    uint64_t value;
    read_lock(&my_rwlock);
    value = my_shared_var;
    read_unlock(&my_rwlock);
    return value;
}
文章来源:https://blog.csdn.net/sz66cm/article/details/135149974
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。