2

首先,我已经有一段时间没有使用任何类型的互斥锁或信号量了,所以请放轻松。

我已经实现了一个通用的日志类,它现在只接收来自其他类的消息,并在该消息前面加上日期/时间和调试级别,然后将消息打印到标准输出。

我想实现某种队列或缓冲区,它将保存许多发送到日志记录类的消息,然后将它们写入文件。

我遇到的问题是我无法决定如何/在哪里保护队列。

以下是我到目前为止提出的一些伪代码:

logMessage(char *msg, int debugLevel){
    formattedMsg = formatMsg(msg, debugLevel) //formats the msg to include date/time & debugLevel
    lockMutext()
    queue.add(formattedMsg)
    unlockMutex()
}

wrtieToFile(){
    if (isMessageAvailable()) { //would check to see if there is a message in the queue
        lockMutext()
        file << queue.getFirst() //would append file with the first available msg from the queue
        unlockMutex()
    }
}

我的问题是:

  • 我真的需要在两个地方都使用互斥锁吗?
  • 互斥锁真的是我想要的吗?
  • 我想我可能需要一个线程来写入文件部分——这听起来是个好主意吗?

仅供参考,我正在寻找一种不使用 Boost 或任何 3rd 方库的方法。

编辑预期的平台是 Linux。

编辑 2将 formatMsg 移到互斥锁之前(谢谢@Paul Rubel)

4

3 回答 3

3

With respect to do you really need the mutex. Think what could happen if you didn't lock things. Unless your queue is thread-safe you probably need to protect both insertion and removal.

Imagine execution contexts changing as you are removing the first element. The add could find the queue in a inconsistent state, and then who knows what could happen.

Regarding creating the message, unless formatMsg makes use of shared resources you can probably more it out of the locked section, which can increase your parallelism.

Extracting the writing to file into its own thread sounds like a reasonable choice, that way the logging threads will not have to make the calls themselves.

于 2013-11-05T15:39:46.493 回答
1

如我错了请纠正我。来自多个线程的多个调用者都试图同时访问相同的资源。

也许您可以只使用一个互斥锁来包装您的全部日志记录功能。

注意比赛条件。

编辑 读者查看对此答案的评论以进行一些有价值的讨论

于 2013-11-05T15:34:48.177 回答
0

You can define a global variable which contains the number of element present in the queue or buffer. That means you need to increment or decrement this variable while adding data or removing data from buffer or queue. So you keep this variable inside a mutex for your above logging framework.

于 2013-11-05T15:44:06.223 回答