Many readers, one writer - is it possible to avoid locking?

前端 未结 5 1066
深忆病人
深忆病人 2021-02-01 06:28

Say you have an in-memory list of strings, and a multi-threaded system, with many readers but just one writer thread.

In general, is it possible to implement this kind o

5条回答
  •  無奈伤痛
    2021-02-01 06:56

    A singly-linked-list approach can be used without locks provided the writer only inserts/deletes at either the head or the tail. In either case, if you construct the new node beforehand, you only need a single atomic operation (head = newHead; or tail.next = newTail) to make the operation visible to the readers.

    In terms of performance, insertions and deletions are O(1), while length calculation is O(n).

提交回复
热议问题