Are threads garbage collected?

Hello! Are ofThreads GC’d after they’re started, if the ThreadedFunction isn’t a loop? If not, what’s the proper way to get rid of unused threads?

Hi @Andyfilms,

Hey have a look at /examples/threads/threadExample for how this class can be used.

ofThread also has a really nice description in the documentation: ofThread | openFrameworks. After reading it, I’m thinking you could call ofThread::stopThread() at any point in the program if you were done with it. I don’t think this will destroy it though.

c++ doesn’t have garbage collection, but has some memory management features. Like all objects in c++, an object of any class that inherits from ofThread will be destroyed if it goes out of scope (on the stack). Objects in dymanic memory (on the heap) can be created and managed with smart pointers, which (if I recall correctly) will also go out of scope when the last of the copies of the object pointed to also goes out of scope or is destroyed. C-style pointers must be deleted with the delete keyword.

You can explicitly call the destructor of an object in c++. I’ve never done it though; I’ve always relied on the scope. I think it goes something like this:

// create a class, this will have default constructor and destructor
class TestClass : public ofThread { // some class-specific code};

// create an instance in ofApp.h
TestClass testClass;

// somewhere in ofApp.cpp
// do some stuff with testClass, and when its finished:
testClass.~TestClass(); // class destructor is called