@Jordi wrote:
Hi all,
I just would like to know about best practices when receiving frames(long chunks of bytes) from callback functions. Could anyone please point me to any addon using callbacks. It would help to compare coding patterns..
I have a couple of questions that have been intriguing me for a while.
The main issue here is that callback functions are unsynced with the ofMainLoop so i guess we need to use a mutex to prevent reading reading/writing from two different threads on the same memory address. So far I use one ofMutex per callback and everything "seems" to be working well. I use mutex.lock() inside the callback and mutex.try_lock() in my update so that we make sure we don-t block the main loop. How does that sound? Is there anything else I should care about?
AFAIK Callback functions cant be member functions unless they are defined as static (something I tired but forced me to redefine to much code as static.. and it produced similar results). It makes sense because callbacks shouldn't be instantiated more than once. Therefore i have to place the callback out of the class and any objects used in the callback have to be also out of the class. I would like to know what is relevant to care about when using non member objects... I'm starting a videoRecorder and seem to hit many issues when storing frames, but not sure if that is related to the fact that they aren't member objects.
Any comments appreciated.
Best,So far my code looks like that:
//---- ofApp.h
class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); Camera device; ofImage liveImage; } ofMutex LiveImageLock; ofPixels RawImage; void ClCallback_Image(ImageStruct* frame, unsigned long dataSize);
//---- ofApp.cpp
void ofApp::update() { if (LiveImageLock.try_lock()) { //----- Mutex begin liveImage.setFromPixels(RawImage); LiveImageLock.unlock(); //----- Mutex end } } void ofApp::draw(){ if (liveImage.isAllocated()) { liveImage.draw(0, 0); } } void ClCallback_Image(ImageStruct* frame, unsigned long dataSize) { LiveImageLock.lock(); //----- Mutex begin CopyImage(&frame->bitmapTop, RawImage, frame->width, frame->height); LiveImageLock.unlock(); //----- Mutex end }
Posts: 4
Participants: 2