c++ - 在锁内对 STL 容器执行耗时操作

标签 c++ multithreading

我有一个存储对象指针的 unordered_map 的 unordered_map。无序映射由多个线程共享。我需要遍历每个对象并执行一些耗时的操作(比如通过网络发送它等)。我如何锁定多个 unordered_map 以使其不会阻塞太久?

typedef std::unordered_map<string, classA*>MAP1;
typedef std::unordered_map<int, MAP1*>MAP2;
MAP2 map2;
pthread_mutex_lock(&mutexA) //how could I lock the maps? Could I reduce the lock granularity?
for(MAP2::iterator it2 = map2.begin; it2 != map2.end; it2++)
{
  for(MAP1::iterator it1 = *(it2->second).begin(); it1 != *(it2->second).end(); it1++)
  {
    //perform some time consuming operation on it1->second eg
    sendToNetwork(*(it1->second));
  }
}
pthread_mutex_unlock(&mutexA)

最佳答案

您可以将所有这些对象存储在一些其他结构(如列表)中并对其进行迭代,这样您就不必锁定映射。

您还可以尝试创建数据的拷贝并处理拷贝 - 这样您的 map 就可以在处理拷贝的同时进行修改。

关于c++ - 在锁内对 STL 容器执行耗时操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4654522/

相关文章:

python - Python asyncio 是否使用线程池?

c++ - glDisable(GL_DEPTH_TEST) 只进行天空球渲染

c++ - 资源 union 引发 SFML 中字体的访问冲突

C# 编译器优化循环?

c++ - 如何避免在 C++ 中进行一些繁重的处理时阻塞线程?

c# - 如何知道WPF中的UI调度程序队列的消息

c++ - Boost Log 更改默认 logging::core 格式化程序?

c++ - Xcode 找不到#Include<> header

c++ - 如何在 Qt Creator 项目向导中添加自定义构建步骤?

c++ - 这个 boost::asio 和 boost::coroutine 使用模式有什么问题?