我有一个类,我试图将它的一些成员函数转换为在不同的线程中运行。虽然程序没有问题,但它在尝试从图像缓冲区(由不同的线程更新)读取时崩溃。似乎问题是由 _beginthread 中的参数传递错误引起的。
下面的代码片段应该更清楚地解释我想要做什么。基本上我想要完成的是让成员函数“fillBuffer”填充图像缓冲区,而其余程序正在做其他事情,包括同时读取相同的图像缓冲区。
非常感谢任何有关语法的帮助。
const int MaxImgBufferSize = 5;
class MyFrame : public wxFrame
{
public:
// constructors
MyFrame(const wxString& title);
private:
static vector <IplImage*> ImgBuffer;
void changeWP(wxCommandEvent&);
void fillBuffer();
void fillBufferFun();
static void __cdecl getImgFromBuffer(void *);
static void __cdecl pushImgBuffer(void *);
};
vector<IplImage*> MyFrame::ImgBuffer;
enter code here
MyFrame::MyFrame(const wxString& title)
: wxFrame(...)
{
// some stuff here
InitializeCriticalSection(&Section);
fillBuffer();
// some code here calls changeWP(wxCommandEvent&) from time to time
}
void MyFrame::fillBuffer()
{
while(ImgBuffer.size() <= MaxImgBufferSize)
{
fillBufferFun();
}
}
void MyFrame::fillBufferFun()
{
ImgBuffer* img;
// do something with img
_beginthread(pushImgBuffer, 0, img);
}
void MyFrame::pushImgBuffer(void *p)
{
EnterCriticalSection(&Section);
ImgBuffer.push_back( (IplImage*) p );
LeaveCriticalSection(&Section);
}
static unsigned int __stdcall getImgFromBuffer(void *);
void MyFrame::changeWP(wxCommandEvent&)
{
// do someting
IplImage* img = NULL;// new IplImage;
_beginthreadex( NULL, 0, MyFrame::getImgFromBuffer, img, 0, NULL );
// do something with img
fillBuffer();
}
unsigned int MyFrame::getImgFromBuffer(void *p)
{
EnterCriticalSection(&Section);
p = (void *)ImgBuffer[0];
ImgBuffer.erase(ImgBuffer.begin());
LeaveCriticalSection(&Section);
return 0;
}