简体   繁体   中英

wxWidgets wxThread Delete for a Joinable Thread

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 thread 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

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.

PS : 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.
    }
}

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 (ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM