这种情况总是经常发生:我们有一些线程和一个共享对象,我们需要确保在任何时候只有一个线程可以修改该对象。
显而易见的解决方案是使用lock the door-do the job-get out of there
习语。在这种情况下,我总是使用POSIX互斥。例如
pthread_mutex_lock(&this->messageRW); // lock the door
P_Message x = this->messageQueue.front(); // do the job
this->messageQueue.pop();
pthread_mutex_unlock(&this->messageRW); // get out of there
// somewhere else, in another thread
while (true) {
P_Message message;
solver->listener->recvMessage(message);
pthread_mutex_lock(&(solver->messageRW)); // lock the door
solver->messageQueue.push(message); // do the job
pthread_mutex_unlock(&(solver->messageRW)); // get out of there
sem_post(&solver->messageCount);
}
我在代码中的许多地方使用messageQueue
。所以最终出现了很多不雅的锁定/解锁配对。我认为应该有一种方法将messageQueue
声明为应该在线程之间共享的对象,然后线程API可以处理锁定/解锁。我可以想到一个包装器类,或者类似的东西。基于POSIX的解决方案是首选的,尽管其他API(提升线程或其他库)也是可以接受的。
在类似的情况下,您会执行什么?
为未来读者更新
我发现了这个。我想这将是C++14的一部分。
在这种情况下,您可以使用boost:scoped_lock
。一旦你超出范围,它就会优雅地解锁:
boost::mutex mMutex;//member mutex object defined somewhere
{ //scope operator start
boost::mutex::scoped_lock scopedLock(mMutex);
pthread_mutex_lock(); // scoped lock the door
P_Message x = this->messageQueue.front(); // do the job
this->messageQueue.pop();
} //scope operator end, unlock mutex
// somewhere else, in another thread
while (true) {
P_Message message;
solver->listener->recvMessage(message);
boost::mutex::scoped_lock scopedLock(mMutex); // scoped lock the door
solver->messageQueue.push(message); // do the job
sem_post(&solver->messageCount);
} //scope operator end, unlock mutex
为此,我将消息队列类的子类(is-a)或包含(has-a)到另一个强制使用互斥的类中。
这在功能上是其他语言所做的,比如Java synchronized
关键字——它修改了要自动保护的底层对象。
消息队列本身应该处理锁定(是原子的),而不是调用代码。你需要的不仅仅是一个互斥对象,您还需要一个条件来避免竞争条件。标准的习语是这样的:
class ScopedLock // You should already have this one anyway
{
pthread_mutex_t& myOwned;
ScopedLock( ScopedLock const& );
ScopedLock& operator=( ScopedLock const& );
public:
ScopedLock( pthread_mutex_t& owned )
: myOwned( owned )
{
pthread_mutex_lock( &myOwned );
}
~ScopedLock()
{
pthread_mutex_unlock( &myOwned );
}
};
class MessageQueue
{
std::deque<Message> myQueue;
pthread_mutex_t myMutex;
pthread_cond_t myCond;
public:
MessageQueue()
{
pthread_mutex_init( &myMutex );
pthread_cond_init( &myCond );
}
void push( Message const& message )
{
ScopedLock( myMutex );
myQueue.push_back( message );
pthread_cond_broadcast( &myCond );
}
Message pop()
{
ScopedLock( myMutex );
while ( myQueue.empty() ) {
pthread_cond_wait( &myCond, &myMutex );
}
Message results = myQueue.front();
myQueue.pop_front();
return results;
}
};
这需要更多的错误处理,但基本结构是那里
当然,如果你能使用C++11,你最好使用标准线程基元。(否则,我通常建议提升线程。但是如果你已经在使用Posix线程可能需要等待转换,直到可以使用标准线程,而不是转换两次。)但你仍然需要互斥锁和条件。