内核lib/kfifo.c中有两个段码,如下:

#define kfifo_in_spinlocked(fifo, buf, n, lock) \
({ \
    unsigned long __flags; \
    unsigned int __ret; \
    spin_lock_irqsave(lock, __flags); \
    __ret = kfifo_in(fifo, buf, n); \
    spin_unlock_irqrestore(lock, __flags); \
    __ret; \
})
static void kfifo_copy_in(struct __kfifo *fifo, const void *src,
    unsigned int len, unsigned int off) {
    unsigned int size = fifo->mask + 1;
    unsigned int esize = fifo->esize;
    unsigned int l;

    off &= fifo->mask;
    if (esize != 1) {
        off *= esize;
        size *= esize;
        len *= esize;
    }
    l = min(len, size - off);

    memcpy(fifo->data + off, src, l);
    memcpy(fifo->data, src + l, len - l);
    /*
     * make sure that the data in the fifo is up to date before
     * incrementing the fifo->in index counter
     */
    smp_wmb();
}

kfifo_in_spinlocked中的函数kfifo_in最终会调用kfifo_copy_in函数,我的问题是,为什么还要使用spin_lock_irqsave,smp_wmb?CPU获得自旋锁使其他CPU停顿,因此它可以独占地修改变量和数据地址,当它解锁时,其他CPU可以获得最新的数据和数据地址?为什么需要smp_wmb

推荐答案

有效地,kfio在SPSC模型(Single生产者Single消费者)中提供无锁访问.而存储器屏障用于来自A reader和A writer的并发访问.

如果有多个生产者(编写者),则需要额外的synchronization between writers个,因此每次只有一个编写者处于活动状态.

功能kfifo_in_spinlocked为写入器之间的这种同步提供了一种方式:自旋锁.

实际上,锁定方面在kfifo.h个标题的最上面进行了描述:

/*
 * Note about locking: There is no locking required until only one reader
 * and one writer is using the fifo and no kfifo_reset() will be called.
 * kfifo_reset_out() can be safely used, until it will be only called
 * in the reader thread.
 * For multiple writer and one reader there is only a need to lock the writer.
 * And vice versa for only one writer and multiple reader there is only a need
 * to lock the reader.
 */

C++相关问答推荐

Apple Libm的罪恶功能

如何将FileFilter添加到FileDialog GTK 4

Mbed TLS:OAEP的就地en—/decryption似乎不起作用'

如何在IF语句中正确使用0.0

C语言中的strstr问题

struct 上的OpenMP缩减

调用mProtection将堆栈上的内存设置为只读,直接导致程序SIGSEGV

在为hashmap创建加载器时,我的存储桶指向它自己

进程在写入管道时挂起

C指针概念分段故障

搜索使用int代替time_t的用法

Go和C中的数据 struct 对齐差异

C语言中奇怪的输出打印数组

C循环条件内的函数

C 和 C++ 标准如何告诉您如何处理它们未涵盖的情况?

函数指针作为函数参数 - 应该使用 const 吗?

C 错误:对 int 数组使用 typedef 时出现不兼容的指针类型问题

当 n 是我们从用户那里获得的整数时,创建 n 个 struct 参数

如何修复数组数据与列标题未对齐的问题?

如何在 C 中的 Postgres 函数的表中 for 循环