Linux基础 - Linux ARM 原子读写

背景

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

接口代码

#include 
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 

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 

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;
}

你可能感兴趣的:(linux,服务器)