【发布时间】:2009-11-17 02:03:49
【问题描述】:
我有一个奇怪的问题,真的不明白发生了什么。
我使用 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 的尝试中,错误发生在_CrtIsValidHeapPointer() 中的dbgheap.c。
Visual Studio 输出它捕获了一个停止点的消息,这可能是由于堆损坏或因为用户按下了 f12(我没有;))
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;
};
和类 Bucket:
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) {/*..*/}
};
谁能告诉我这可能是什么问题?
edit:这是我从线程调用的另一个静态函数。这样做安全吗?
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 是如何被另一个线程重新输入的?你想同步访问什么?
-
我在顶部添加了创建线程的代码。 m_bucketCreator 是一个静态成员变量,被多个线程访问
标签: multithreading mfc