Thread Anatomy

i’m coding an application that makes requests to the network to gather data.

when i make a request in order to get the data and parse it, the app freezes until everything is done and then resumes the normal activities (the draw() loop).

in order to stop this freezing, i know that a thread must be created where all the communications and parsing must be done.

the thread addon has a almost non existent documentation, which makes it difficult to understand how it works.

From what i’ve seem to understand, inside the void threadedFunction is where i should write my code.

i don’t understand is the void draw() in threadedObject.h and the lock() and unlock().

what i want to do is

user presses button (this then runs TO.start() where TO is a threadedObject ) -> thread starts -> makes network request -> gathers data -> parses data -> thread ends.

would this be correct?

void threadedFunction(){  
			while( isThreadRunning() != 0 ){  
				if( lock() ){  
					//get network data  
					//parse data  
					ofSleepMillis(1 * 1000);  

i’ve read in the forums that the thread doesn’t execute functions except for those defined inside the thread, but can it use variables from outside?

Hi Bruno

A thread is a different process that runs simultaneously and independently from your main thread (your main thread in this case is whats happening in your testApp, your second thread is what you write inside threadedFunction()). A thread will run at a different framerate and will not be in sync with your testApp. For this reason its not a good idea to share variables and other data between threads when they are running simultaneously, it can result in weird behavior and crashes.

In your case what you could do is, every time someone presses the button:

  1. make sure your threadedFunction is not already running (if it is you can ignore the button press, wait till it is finished and then proceed, etc…)
  2. copy all the necessary data into your threaded object
  3. run the threaded function only once to make the network request, parse the data, etc…
  4. in your testApp, start to check on every frame if your thread has finished doing its thing
  5. if it has finished, copy the necessary data back from your thread into testApp

the ideia is that you will only exchange data with your thread when it is not running!

I have an addon called ofxRuiThread with methods that simplify this sort of thing. If you want you can get it here .

Threads are evil.

hope it helps


got the simpleThread working :smiley: :smiley: .
basic setup at the moment, makes request gets the values by using updateOnce();
got to get things working with the variables now.

Obrigadão Rui.