Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 如果有足够的内存,当只有一个专用写入线程时是否不需要锁?_Multithreading_Locking_Mutex_Atomic_Lockless - Fatal编程技术网

Multithreading 如果有足够的内存,当只有一个专用写入线程时是否不需要锁?

Multithreading 如果有足够的内存,当只有一个专用写入线程时是否不需要锁?,multithreading,locking,mutex,atomic,lockless,Multithreading,Locking,Mutex,Atomic,Lockless,对于具有多个读线程和一个写线程的场景,允许读线程读取稍微过时的数据,我以伪代码的最基本形式炮制了一个无锁控制流,如下所示: GLOBAL_ATOMIC_POINTER shared_pointer // Only called by the reader threads. read() THREAD_LOCAL_POINTER read_pointer := shared_pointer return read_data_at(read_pointer) // Only ca

对于具有多个读线程和一个写线程的场景,允许读线程读取稍微过时的数据,我以伪代码的最基本形式炮制了一个无锁控制流,如下所示:

GLOBAL_ATOMIC_POINTER shared_pointer

// Only called by the reader threads.
read()
    THREAD_LOCAL_POINTER read_pointer := shared_pointer
    return read_data_at(read_pointer)

// Only called by the writer thread.
write(input)
    THREAD_LOCAL_ARRAY array
    THREAD_LOCAL_POINTER write_pointer := shared_pointer
    if write_pointer == location_of_last_element(array)
        write_pointer := location_of_first_element(array)
    else
        write_pointer := location_of_next_element(array, write_pointer)
    write_data_at(write_pointer, input)
    shared_pointer := write_pointer
让我们调用
MAX\u READING\u DURATION
调用
read()
可以完成的最长时间段,以及
MIN\u write\u DURATION
调用
write()
可以完成的最短时间段

现在,由于
共享指针
保证是原子的,只要
最大读取持续时间
,这个方案就应该是完全安全的


还是我忽略了什么?如果不是,我相信这是一件众所周知的事情,我想知道正确的术语是什么,所以当我向其他人解释/提倡这种方法时,我可以使用它。

足够的内存和写入线程的总数不是决定什么可以和不可以是无锁的标准

无锁编程的一个重要特性是,如果挂起一个线程,它将永远不会阻止其他线程通过自己的无锁操作取得进展

但是,更重要的是:您的(单个编写器)代码需要遵守的主要特性是“顺序一致性”,以实现无锁:

顺序一致性意味着“所有线程都同意内存操作的发生顺序,并且该顺序与程序源代码中的操作顺序一致”

如果代码不能保证顺序一致性,则必须防止内存重新排序。(以下是有关内存重新排序的更多信息:)

最后,我建议查看这些资源,以深入了解无锁多线程编程概念:

祝你好运