我有一个奇怪的问题,真的不明白发生了什么事情。MFC多线程与删除[],dbgheap.c
我让我的应用程序使用MFC多线程多线程。
一切运作良好,到目前为止,但现在:
某处在代码的开头我创建线程:
m_bucketCreator = new BucketCreator(128,128,32);
CEvent* updateEvent = new CEvent(FALSE, FALSE);
CWinThread** threads = new CWinThread*[numThreads];
for(int i=0; i<8; i++){
threads[i]=AfxBeginThread(&MyClass::threadfunction, updateEvent);
m_activeRenderThreads++;
}
这将创建8个线程此功能工作:
UINT MyClass::threadfunction(LPVOID params) //executed in new Thread
{
Bucket* bucket=m_bucketCreator.getNextBucket();
...do something with bucket...
delete bucket;
}
m_bucketCreator
是一个静态成员。现在我在Bucket的解构器中得到了一些线程错误,试图删除一个缓冲区(但是,我明白这个缓冲区应该在这个线程的内存中,所以我不明白为什么会有错误)。在尝试delete[] buffer
时,错误发生在dbgheap.c
的_CrtIsValidHeapPointer()
中。
视觉工作室输出,它捕获一停止点该消息并且这可以是由于堆损坏或因为用户按下F12(I没有;))
class BucketCreator {
public:
BucketCreator();
~BucketCreator(void);
void init(int resX, int resY, int bucketSize);
Bucket* getNextBucket(){
Bucket* bucket=NULL;
//enter critical section
CSingleLock singleLock(&m_criticalSection);
singleLock.Lock();
int height = min(m_resolutionY-m_nextY,m_bucketSize);
int width = min(m_resolutionX-m_nextX,m_bucketSize);
bucket = new Bucket(width, height);
//leave critical section
singleLock.Unlock();
return bucket;
}
private:
int m_resolutionX;
int m_resolutionY;
int m_bucketSize;
int m_nextX;
int m_nextY;
//multithreading:
CCriticalSection m_criticalSection;
};
和类铲斗:
class Bucket : public CObject{
DECLARE_DYNAMIC(RenderBucket)
public:
Bucket(int a_resX, int a_resY){
resX = a_resX;
resY = a_resY;
buffer = new float[3 * resX * resY];
int buffersize = 3*resX * resY;
for (int i=0; i<buffersize; i++){
buffer[i] = 0;
}
}
~Bucket(void){
delete[] buffer;
buffer=NULL;
}
int getResX(){return resX;}
int getResY(){return resY;}
float* getBuffer(){return buffer;}
private:
int resX;
int resY;
float* buffer;
Bucket& operator = (const Bucket& other) { /*..*/}
Bucket(const Bucket& other) {/*..*/}
};
有谁能告诉我这里可能是什么问题?
编辑:这是我从线程调用的其他静态函数。这是安全的吗?
static std::vector<Vector3> generate_poisson(double width, double height, double min_dist, int k, std::vector<std::vector<Vector3> > existingPoints)
{
CSingleLock singleLock(&m_criticalSection);
singleLock.Lock();
std::vector<Vector3> samplePoints = std::vector<Vector3>();
...fill the vector...
singleLock.Unlock();
return samplePoints;
}
为什么要对关键部分进行锁定以分配新的存储桶对象? getNextBucket如何被另一个线程重新输入?你在试图同步访问什么? – 2009-11-17 02:15:25
我添加了代码,我在顶部创建线程。 m_bucketCreator是一个由多线程访问的静态成员变量 – Mat 2009-11-17 02:21:00