【发布时间】: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