【发布时间】:2019-01-13 15:33:17
【问题描述】:
我有一个关于生产者消费者问题的基本问题。请考虑以下伪代码。
// Consumer. This is in the thread I created for asynchronous log writing
// so that I don't block the important threads with my silly log-writing
// operation
run()
{
mutex.lock(); // Line A
retrieveFromQueueAndWriteToFile();
mutex.unlock();
}
// producer. This function gets log messages from 'x' number of threads
add( string mylog )
{
mutex.lock(); // Line B, consider internal call to pthread_mutex_lock
Queue.push(mylog);
mutex.lock();
}
当日志写入操作在消费者函数中进行时,互斥锁被保持在那里。所以,当一个新的日志进来时,在 B 行,在 add 函数中无法获得互斥锁。当日志写入操作发生时,这会阻塞重要的线程。
这与将日志写入文件与其他重要线程本身不同吗?当重要的线程无论如何都被阻塞时,我没有看到创建一个新线程将日志写入文件的意义。
任何帮助表示赞赏。
【问题讨论】:
标签: c++ mutex producer-consumer