互斥体在生产者-消费者问题中阻塞线程

Mutex blocking the thread in a producer-consumer problem

本文关键字:问题 线程 消费者 生产者      更新时间:2023-10-16

我有一个关于生产者消费者问题的基本问题。请考虑以下伪代码。

//  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 函数中获取互斥锁。这会在发生日志写入操作时阻止重要线程。

这与使用其他重要线程本身将日志写入文件不同吗?无论如何,当重要线程被阻止时,我认为创建一个新线程将日志写入文件没有意义。
任何帮助表示赞赏。

您可以将 retrieveFromQueueAndWriteToFile 拆分为:retrieveFromQueue 和 writeLogToFile。像这样:

run()
{
    mutex.lock();  // Line A
    auto log = retrieveFromQueue();
    mutex.unlock();
    writeLogToFile(log); // this operation does not need a lock
}

注意:如果 run 仅由无限循环中的一个线程调用,则仅锁定队列中的推送和弹出,则操作的写入文件部分由该线程完成而不锁定。