【发布时间】:2020-05-17 11:15:02
【问题描述】:
我编写了一个自定义节流器来处理当某些客户端(即进行外部调用)出现退避异常并需要在进行另一个 API 调用之前休眠时的场景。
我的内存转储有一个奇怪的场景:卡在无限循环中,尽管我看不出有什么原因。 此应用程序有许多线程,并且所有客户端调用都使用以下代码进行限制。 对某些 API 的调用是这样完成的:
bool res = DoSomeAction([&]{ /* call client m_client.callAPI()*/ return true}
内存转储显示只有 1 个线程在工作(通常有 10 个),并且 m_isThrottling 设置为 true,因此整个应用程序一直在运行。
这种情况怎么会发生?有什么更好的实现建议(带 m_ 前缀的变量表示类变量,m_throttlingTime 和 m_isThrottling 是静态类变量)?
template<typename T>
bool ThrottlerClass::DoSomeAction(T && lambda)
{
for (int retriesCount = 3; retriesCount > 0; --retriesCount)
{
while (m_isThrottling) //dump is stuck here
{
Sleep(10000);
}
try
{
return lambda();
}
catch (const std::exception& ex)
{
int time = m_client->GetThrottlingTimeMS(); //the client got exception making API call and saves it
if (time > 0)
{
ExclusiveLock lock(&m_throttlingMutex); //custom scope mutex
m_isThrottling = true;
if (time > m_throttlingTime)
m_throttlingTime = time;
}
if (m_throttlingTime > 0)
{
Sleep(m_throttlingTime);
{
ExclusiveLock lock(&m_throttlingMutex);
m_isThrottling = false;
m_throttlingTime = 0;
}
}
continue;
}
}
return false;
}
【问题讨论】:
标签: c++ concurrency throttling