gpt4 book ai didi

c++ - 互斥保护 : is there any automated protection mechanism for objects?

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:24 24 4
gpt4 key购买 nike

这种情况总是经常发生:我们有一些线程,和一个共享对象,我们需要确保在任何时候都只有一个线程可以修改该对象。

好吧,显而易见的解决方案是使用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(增强线程或其他库)。

在类似情况下您会实现什么?

为 future 的读者更新

我找到了 this .我猜将成为 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

关于c++ - 互斥保护 : is there any automated protection mechanism for objects?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17442782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com