gpt4 book ai didi

c++ - 这是使用没有互斥量的条件变量的安全方法吗

转载 作者:行者123 更新时间:2023-11-30 01:57:17 24 4
gpt4 key购买 nike

我现在的代码是这样的

void XXX::waitForUpdates()
{
boost::unique_lock<boost::mutex> lock(mutex_agentDone);
while(!allAgentUpdatesDone()) {
COND_VAR_AGENT_DONE.wait(lock);
}
}

void XXX::onAgentUpdate(YYY argums){
Agent * target = const_cast<Agent*>(argums.GetAgent());
boost::unique_lock<boost::mutex> lock(mutex_agentDone);
REGISTERED_AGENTS.setDone(target,true);
COND_VAR_AGENT_DONE.notify_all();
}

一切都很好,除了当 onAgentUpdate 每 1 秒被调用大约一百万次时,我不得不担心性能和优化。

所以我想如果我将 wait(lock) 更改为执行 allAgentUpdatesDone() 检查的 timed_wait 版本,我可以跳过 .notify(),否则每秒会调用数十万次!别急,这是一个模拟框架:)

然后我问自己:我需要 mutex_agentDone 做什么?我可以像这样修改这两个函数:

void XXX::waitForUpdates()
{
//this lock will become practically useless, coz there is no other
// mutex_agentDone being locked in any other function.
boost::unique_lock<boost::mutex> lock(mutex_agentDone);
while(!allAgentUpdatesDone()) {
COND_VAR_AGENT_DONE.timed_wait(lock,some_time_interval);
}
}

void XXX::onAgentUpdate(YYY argums){
Agent * target = const_cast<Agent*>(argums.GetAgent());
REGISTERED_AGENTS.setDone(target,true)
}

问题是:这样安全吗?

谢谢

小提示:假设这两个函数中的其余操作已经由它们自己的互斥体保护(REGISTERED_AGENTS 是一个具有容器 和它自己的互斥体 的类对象> 在每个访问器和迭代方法中被调用,所以 allAgentUpdatesDone() 使用与 REGISTERED_AGENTS 相同的 mutex 迭代相同的 container)

最佳答案

你可以这样做:

void XXX::waitForUpdates()
{
boost::unique_lock<boost::mutex> lock(mutex_agentDone);
while(!allAgentUpdatesDone()) {
++waiters;
COND_VAR_AGENT_DONE.wait(lock);
--waiters;
}
}

void XXX::onAgentUpdate(YYY argums){
Agent * target = const_cast<Agent*>(argums.GetAgent());
boost::unique_lock<boost::mutex> lock(mutex_agentDone);
REGISTERED_AGENTS.setDone(target,true);
if (waiters != 0)
COND_VAR_AGENT_DONE.notify_all();
}

互斥体保护 waiters 计数。确保将其设置为零以开始。

您可能希望条件变量已经有这样的东西,但调用 notify_all 的开销可能很重要。

这假设大部分时间没有服务员。如果问题是大部分时间 allAgentUpdatesDone 返回 false,则不要调用 notify_all 除非 all 更新完成了。

关于c++ - 这是使用没有互斥量的条件变量的安全方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18887139/

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