Reputation: 13
I have a class which I am trying to convert some of its member function to run in different threads. While the program complies without problem, but it crashes when it is trying to read from a image buffer(which is updated by a different thread). Seems like the problem is cause by when argument is passed incorrectly in _beginthread.
The following snippet of code should explain more clearly what I am trying to do. Basically what I am trying to accomplish is have member function "fillBuffer" fill a image buffer while rest of program is doing something else including reading the same image buffer at the same time.
Any help with the syntax is greatly appreciated.
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;
}
Upvotes: 1
Views: 1186
Reputation: 3530
There are a couple of issues here:
void MyFrame::changeWP(wxCommandEvent&) { IplImage* img = NULL; // No memory leak, this time. _beginthread(MyFrame::getImgFromBuffer, 0, & img); //... } void MyFrame::getImgFromBuffer(void ** p) { //... *p = (void *)ImgBuffer[0]; //... }
There's probably more, but this is enough to start with.
Upvotes: 1