我的工作在多螺纹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

如果你使用一个清单与外部节点,然后你可能会想要分配的存储器之外的互斥锁,只是为了减少时其举行。但如果你设计的事件与一个侵入式列表中的节点,或许最简单的。

编辑:你还可以支持多的读者(没有便携式保证对这一个被某一特定事件)如果在取消你改变"信号""广播"。虽然你不需要它时,它并不真正任何费用。

其他提示

如果你不需要一个锁免费排队,然后你可以总结现有的队列与锁。

Mutex myQueueLock;
Queue myQueue; 
void mtQueuePush(int value)
{
    lock(myQueueLock);
    queuePush(myQueue, value);
    unlock(myQueueLock);
}
int mtQueueNext()
{
    lock(myQueueLock);
    int value = queueFront(myQueue);
    queuePop(myQueue);
    unlock(myQueueLock);
    return value;
}

唯一的事情之后,添加某种handeling为mtQueueNext时,队列是空的。

编辑:如果你有一个单一的读者,单个作家无锁定排队,你只需要有一个锁周围mtQueuePush,以防止多个同时作家。

那里有一个保险带的单一的读者/作家无锁定的排队周围,当他们大多是作为实现c++模板课程。但是做一个谷歌搜索以及如果需要的工作,如何改写他们在普通C。

http://www.liblfds.org

锁定的免费数据的结构图书馆编写C。

有的M&S的队列。

我会去的多个单写队(每个作家螺纹)。然后你可以检查 对于如何获得单一的读者阅读的各种各样的队列。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top