【发布时间】:2020-01-31 20:19:01
【问题描述】:
我有一个可以通知对象的类处理器。 通知对象最终会在单独的线程中处理。
由于队列在不同线程之间共享,因此需要一个互斥体q_mutex 来防止错误行为。
class Processor {
std::queue<int> q;
void q_processing_thread(); // while true loop - uses the mutex
public:
void notify(int); // pushes int to q - uses the mutex
bool isEmpty() const; // checks if the queue is empty - uses the mutex
};
问题:
互斥锁应该是处理器的属性还是全局变量?
从概念上来说,
-
isEmpty应该是const因为它不应该改变对象。然而,这阻止了它 锁定互斥锁。 - 互斥体在类之外没有意义,因为队列是处理器的私有属性。
【问题讨论】:
-
制作互斥锁
mutable。这允许您在const方法中更改它。
标签: c++ multithreading oop mutex