gpt4 book ai didi

c - C中的多编写器线程安全队列

转载 作者:太空狗 更新时间:2023-10-29 16:37:41 26 4
gpt4 key购买 nike

我正在使用 pthreads 开发多线程 C 应用程序。我有一个写入数据库的线程(数据库库只能在单个线程中安全使用),还有几个线程正在收集数据、处理数据,然后需要将结果发送到数据库线程进行存储。我已经看到提到在 C 中创建一个多作者安全队列是“可能的”,但是我看到这个提到的每个地方都只是说它“对于这个例子来说太复杂了”并且仅仅演示了一个单一作者安全队列.

我需要以下东西:

  • 高效的插入和移除。我假设像任何其他队列一样,O(1) 入队和出队是可能的。
  • 动态分配的内存,即链接结构。我不需要对队列的大小有任意限制,所以数组真的不是我想要的。

编辑: 读取线程不应该在空队列上自旋,因为可能有几分钟没有写入,短时间突发大量写入。

最佳答案

当然,有无锁队列。不过,根据您在评论中所说的内容,这里的性能一点也不重要,因为无论如何您都会为每次写入创建一个线程。

因此,这是条件变量的标准用例。使自己成为一个包含互斥锁、条件变量、链表(或循环缓冲区,如果你喜欢的话)和取消标志的结构:

write:
lock the mutex
(optionally - check the cancel flag to prevent leaks of stuff on the list)
add the event to the list
signal the condition variable
unlock the mutex

read:
lock the mutex
while (list is empty AND cancel is false):
wait on the condition variable with the mutex
if cancel is false: // or "if list non-empty", depending on cancel semantics
remove an event from the list
unlock the mutex
return event if we have one, else NULL meaning "cancelled"

cancel:
lock the mutex
set the cancel flag
(optionally - dispose of anything on the list, since the reader will quit)
signal the condition variable
unlock the mutex

如果您正在使用带有外部节点的列表,那么您可能希望在互斥锁之外分配内存,只是为了减少它的持有时间。但是,如果您使用可能最简单的侵入式列表节点来设计事件。

编辑:如果在取消时将“信号”更改为“广播”,您还可以支持多个阅读器(没有可移植的保证)。虽然您不需要它,但实际上也不需要任何费用。

关于c - C中的多编写器线程安全队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1212623/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com