16
System / Thread startet from a Thread
« on: August 25, 2009, 05:52:24 am »
"delete this" is okay if you never allocate that variable to stack.
Small example to illustrate this:
So, you want to launch x number of threads and see that they will get freed when they are done?
Maybe just store them in a list? And wait them to finish
Small example to illustrate this:
Code: [Select]
class Foo
{
void del(void)
{
delete this;
}
}
Not okay:
{
class Foo tmp;
tmp.del(); // Deletes the pointer
} // Variable tmp goes out of scope, destructor will be called again, undefined behavior
Okay:
{
class Foo *tmp= new Foo;
tmp.del(); // Deletes the pointer
}
But since this can lead into very interesting bugs, I would recommend you doing something else So, you want to launch x number of threads and see that they will get freed when they are done?
Maybe just store them in a list? And wait them to finish
Code: [Select]
#include <list>
// List for allocated threads
std::list <sf::Thread *> CreatedThreads;
class TC1 : public sf::Thread{
private :
virtual void Run()
{
std::cout << "I'm the main thread" << std::endl;
// Print something...
for (int i = 0; i < 10; ++i)
{
TC2 *tc = new TC2;
CreatedThreads.push_back(tc); // Store the thread pointer
tc->number = i;
tc->Launch();
}
}
};
int main(int argc, char** argv)
{
TC1 tc;
tc.Launch();
system("PAUSE"); // Needed in this example for TC1 thread to run before next line
// Wait all threads to finish
while (!CreatedThreads.empty())
{
sf::Thread *Thread=CreatedThreads.front();
CreatedThreads.pop_front();
// Wait thread to finish and free memory when done
Thread->Wait();
delete Thread;
}
}