我有一個奇怪的問題,真的不明白髮生了什麼事情。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