【问题标题】:How can I get a least recently used algorithm to work with multiple threads?如何获得最近最少使用的算法来处理多个线程?
【发布时间】:2010-07-11 01:02:04
【问题描述】:

我正在使用内存池将图像数据存储在光线追踪器中,并且我正在使用最近最少使用的算法来处理释放内存块。当只有一个线程时,这可以正常工作。当我添加更多线程时,LRU 代码会中断。我正在使用链表来存储已访问哪些块的历史记录,这是中断的部分,因为在访问块时,我必须修改链表中的指针,这会导致线程之间发生冲突。这是我能想到的实现内存池的唯一方法,所以我不确定如何让它工作。

这是我用来将访问的块放在最近使用的列表前面的代码,其中发生了内存读取错误:

    LinkedListNode<int> *curTextureIndex = lastUsedTexture;
    LinkedListNode<int> *prevTextureIndex = NULL;
    //Find the requested texture in the recently used list
    while(curTextureIndex->data != textureBlockIndex)
    {
        prevTextureIndex = curTextureIndex;
        curTextureIndex = curTextureIndex->next;
    }

    if(curTextureIndex != lastUsedTexture)
    {
        //Bring this block to the front of the accessed list
        if(prevTextureIndex != NULL)
            prevTextureIndex->next = curTextureIndex->next;
        curTextureIndex->next = lastUsedTexture;
        lastUsedTexture = curTextureIndex;

        //Set the tail of the list if necessary
        if(lastUsedTexture_tail == curTextureIndex && prevTextureIndex != NULL)
            lastUsedTexture_tail = prevTextureIndex;
    }

有没有一种很好的方法来实现它,以便它可以很好地与多个线程一起工作?

【问题讨论】:

  • 您需要锁定共享池或为每个线程提供自己的池。您没有发布足够的代码来提供更多详细信息。
  • 锁定似乎是一个不错的解决方案,尽管我对此了解不多。我不想创建多个池,因为池中的数据是从文件中读取的,线程可能需要一些相同的数据。

标签: c++ algorithm multithreading


【解决方案1】:

您可以尝试使用临界区。在此处查看 wiki 页面:http://en.wikipedia.org/wiki/Critical_section

如果您使用 ATL 或 MFC,它们有自己的类,这些类包含您可能会发现更容易使用的低级对象。

对于 MFC:CCriticalSection

对于 ATL:CComAutoCriticalSection

你可以把所有的链表操作代码放在一个临界区,你不会有一个线程践踏链表,而另一个线程正在处理它。

另外,对于 LRU 缓存,我建议您使用双向链表和列表指针的哈希表(key = textureBlockIndex)来快速获取条目,而不是遍历列表并进行比较,这会让它变慢。

加快速度将确保您在关键部分花费的时间很少,这是一件好事。

见:LRU cache design

【讨论】:

  • 谢谢。关键部分正是我想要的。使用哈希表听起来也不错。
猜你喜欢
  • 2016-08-31
  • 2017-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-15
相关资源
最近更新 更多