Search code examples
c++multithreadingwxwidgets

Strange behavior when multithreading using wxWidgets


There are 2 threads in my application - one UI, and the second is updating some data. The class of the second thread inherits the wxThread class, and has some variables, in particular, Worker *worker.

class Worker {
public:
    virtual void work() {}
};

class WorkerThread : public wxThread {
public:
    bool isRunning = true;
    Worker *worker;

    virtual ExitCode Entry() {
        while (isRunning) {
            if (worker == nullptr) continue;
            worker->work();
            usleep(UPDATE_DELAY_USEC);
        }

        std::cout << "Done\n";

        return 0;
    }
};

If I change the value of the worker from the first thread to nullptr, the application will continue working fine. If, for example, I change the value to new Worker() or the same value as it was, the application will simply exit. Without any errors printed to the console.

I change this pointer in wxNotebook events:

void onPageChanged(wxBookCtrlEvent &event) {
    switch (event.GetOldSelection()) {
        case MNP_PROCESSES:
            workerThread->worker = nullptr;
            break;
    }

    switch (event.GetSelection()) {
        case MNP_PROCESSES:
            workerThread->worker = &processes->worker;
            break;
    }
}

The whole strange thing is that if I bring the Worker *worker to the global scope, then everything will work fine, without any errors.

Worker *worker;

class WorkerThread : public wxThread {
    ...

What is the reason?


Solution

  • The problem was solved. I was looking for a problem where there is none. The problem was that I first created a wxNotebook, respectively, onPageChanged was called, in which the pointer changed, which belonged to a class that had not yet been created.