互斥体在生产者-消费者问题中阻塞线程
Mutex blocking the thread in a producer-consumer problem
我有一个关于生产者消费者问题的基本问题。请考虑以下伪代码。
// 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 仅由无限循环中的一个线程调用,则仅锁定队列中的推送和弹出,则操作的写入文件部分由该线程完成而不锁定。
相关文章:
- 使用 ubuntu 终端在 c++ 上运行线程类的问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 尝试从头开始实现Leetcode的FizzBuzz多线程问题。收到"libc++abi.dylib: terminating"错误
- 餐饮哲学家问题 - 只有 2 个线程工作
- 线程过程中的线程同步问题
- 在 C++ 的 Qt 中使用 WINAPI 线程时出现问题
- 线程和互斥锁的使用有什么问题
- 并发问题:如何只有一个线程通过关键部分
- MFC执行线程问题
- 在多线程函数中返回共享的常量指针会导致计时问题吗?
- C++多线程生产者-消费者问题
- C++ 多线程中的锁和条件变量问题
- 线程清理器检测到数据争用,问题出在哪里?
- 编译问题 C++ 同时,尝试通过调用另一个对象中的成员函数来创建 std:: 线程
- 多线程与线程小问题
- 线程池 C++ 实现问题
- 提升线程问题,当一个线程与另一个线程没有相同的副本时如何共享变量?
- 如何修复macOS线程互斥锁性能缓慢的问题?
- 多线程概念问题
- 迷宫构造函数问题 [线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x8)]