Multiple-writer thread-safe queue in C

后端 未结 4 1015
旧巷少年郎
旧巷少年郎 2020-12-08 03:21

I am working on a multi-threaded C application using pthreads. I have one thread which writes to a a database (the database library is only safe to be used in a single threa

4条回答
  •  执笔经年
    2020-12-08 04:02

    If you dont need a lock free queue, then you could just wrap up an existing queue with a lock.

    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;
    }
    

    The only thing after that is to add some sort of handling for mtQueueNext when the queue is empty.

    EDIT: If you have a single reader, single writer lockless queue, you only need to have a lock around mtQueuePush, to prevent multiple simultaneous writers.

    There are a number of single reader/writer lockless queues around, however most of them are implemented as c++ template classes. However do a google search and if need be work out how to rewrite them in plain C.

提交回复
热议问题