ofBuffer and threads

Hi guys,

I seem to run into a problem which I can’t figure out using ofBuffer in threads.
I am trying to copy pixels in buffer inside a thread but that does not seem to work.

Here is an example:

//--------------------------------------------------------------
void NCTCPThreaded::setup() {
    image.load("image.jpg");
}

//------------------------------------------------------------
void NCTCPThreaded::draw() {
    imageback.draw(0,0);
}

//--------------------------------------------------------------
void NCTCPThreaded::doPixelStuff() {
	ofBuffer buffer;
	ofSaveImage(image.getPixelsRef(), buffer, OF_IMAGE_FORMAT_JPEG, OF_IMAGE_QUALITY_HIGH);
	ofLoadImage(pixels, buffer);
	imageback.setFromPixels(pixels);
}

//--------------------------------------------------------------
void NCTCPThreaded::threadedFunction() {
	while (isThreadRunning()) {
		lock();
			doPixelStuff();
		unlock();
      }
}

So if I call the function doPixelStuff() from within the thread all I get is a white picture.

When I call the function doPixelStuff() from outside the thread it works just fine.

I also tried memcpy but that just crashes
memcpy(pixels.getPixels(), buffer.getData(), buffer.size());

If anybody knows what is going on here, I would be glad to hear it :slight_smile:

Thanks!

you can’t upload the data to the gpu from the thread which is what imageback.setFromPixels is doing among other things. the easiest is to have the thread save the pixels to the buffer, load them back to an ofPixels instead of to an ofImage and then in the main thread upload the pixels to a texture.

as you are doing it though you’ll get tearing in the image surely since you are not locking the main thread. look into using ofThreadChannel which makes this much easier:

Hi Arturo,

Thank you so much! It works. You are right about the image tearing. When I do lock the image in the main thread, it’s becoming very slow. I will definitely have to check ofThreadChannel.

What I am actually trying to do is to send custom classes over TCP and I was using the image just to test.
I know this is another question but do you know how to send a vector over the network?
I am messing up the size of the object I guess.

Like so:

     vector<ofVec3f> vectors;
		for (int i = 0; i < 100; i++) {
			ofVec3f myvec = ofVec3f(ofRandom(100), ofRandom(100), ofRandom(100));
			vectors.push_back(myvec);
		}

    int size = sizeof(vectors) + (vectors.size()*sizeof(ofVec3f));

    ofBuffer mybuffer;
    mybuffer.set((const char*)&vectors, size);

I guess something is wrong with the size because on the other side I can not get it back right. It crashes.

While when I only send one ofVec3f and I use just this sizeof(ofVec3f), it works great.

Thanks!