Edit public variable value inside another thread using threadedFunction

Hello,

I’m starting a new project and I need to save a vector of meshes as ply files every 5 minutes.

I am doing it using a second thread. I have written a class MyThread based on this example:

http://openframeworks.cc/documentation/utils/ofThread/

Everything works fine: I am able to exchange data between the ofApp.ccp and the header of MyThread using the function update() located in ofApp.ccp using code like this:

myImage = thread.image;

But how can I do the exact opposite ?

Obviously thread.image = myImage won’t work.

If I put this line of code in the threadedFunction() defined in the header of the class MyThread I am not able to recognize “myImage”.

To sum up, how can I access and edit “myImage” (or any public variable declared in the header of ofApp) inside the threadedFunction() defined at the adress below ?

http://openframeworks.cc/documentation/utils/ofThread/

Depending on your use of the ofImage inside of the thread thread.image = myImage could work. This however is going to copy the image you also have to be careful as ofImage contains an ofTexture which has to be manipulated on the main thread or you will crash.

if you want MyThread to have direct access to what is in ofApp the easiest way is to pass a pointer to it.

MyThread.h
ofImage* image;

//ofApp
threadImage.image = &myImage;

You also have to be careful that you are not manipulating the myImage at the same time that MyThread is manipulating it.

A safer way to deal with the ofImage in the new thread is to pass the ofPixels object instead of the whole ofImage object.

Like

MyThread.h
ofPixels* pixels;

//ofApp
thread.pixels = &myImage.getPixels();

Even more safe would be to copy the pixels instead of using a pointer.

What you asked about making all the elements of ofApp visible to the MyThread object.
Considering that your MyThread object is inside the ofApp.

forward declare ofApp inside MyThread.h file

class ofApp;

class MyThread:public ofThread {
public:

ofApp* ofAppPointer;
ofPixels pixels;
float whateverElse;
......
......
};

Then in ofApp, probably setup() add the following:

thread.ofAppPointer = this;

Then you can access any ofApp public method or property

// from inside MyThread
if(ofAppPointer){//It is a good idea to check if it is a null pointer,
    ofAppPointer->image.doWhatEver()
    ofAppPointer->whateverElse = 2* someOtherNumber;
}

Finally remember that any change you make to the pixels of an ofImage you will need to call image.update() so this changes become visible and always call it from within the main thread otherwise it will crash.

Hope it helps.

Best

1 Like

Hello,

Thank you both for your advices. They have been a great help.

Best