I got a question about joinable threads in wxWidgets.
When the user wants it, I want to stop a thread doing some work. For that reason I call in this worker thread TestDestroy() to check whether the t开发者_StackOverflow中文版hread should be stopped. But I can only stop the thread this way by calling Delete(), which should not be called for joinable threads.
Is there a possibility for me to stop the thread (using TestDestroy) or do I have to change my code completely?
Thanks in advance,
TiBo
The current documentation for wxThread::Delete() says:
This function works on a joinable thread but in that case makes the TestDestroy() function of the thread return true and then waits for its completion (i.e. it differs from Wait() because it asks the thread to terminate before waiting).
So, it appears that you can use Delete()
on a joinable thread.
You have to call the Exit() method from your worker thread or simply return from the Run method AND call the MyThread->Wait() method then delete the thread object.
Declaring the thread :
class MyThread : public wxThread {
virtual void * run();
};
Thread implementation :
MyThread::run()
{
while(1)
{
if(TestDestroy())
{
this.Exit(); // or return;
}
// Do some work
}
}
Declaring the Thread pointer :
MyThread * pMyThread;
Creating, launching and stopping the thread
void launchThread{
pMyThread = new wxThread(wxTHREAD_JOINABLE);
pMyThread->Create();
pMyThread->Run();
}
void stopThread(){
pMyThread->Delete();
pMyThread->Wait();
delete pMyThread;
}
Hope that it helps.
P.S. : this is my first answer on Stack Overflow. I don't know how I can easilly write some code automatically indented?
You shouldn't have to rewrite your code.
It's usually best that a thread terminates by returning from it's main function, as the documentation suggests.
One way of achieving this, and probably the easiest, is to throw some object that will be caught in the main thread function.
For example:
struct ThreadEndingException { };
void DoSomeWork() {
...
if (TestDestroy())
throw ThreadEndingException();
...
}
void ThreadFunction() {
try {
DoSomeWork();
}
catch (const ThreadEndingException&) {
// Do nothing, the function will return after leaving this catch.
}
}
精彩评论