0

Firstly, this is the first time I use multithreading, so, forgive me.
I found a subject talking about threads in wxWidgets, and I have created an example to use threads, but I don't know if that code works correctly, because it doesn't take any time to be executed.

#include <wx/thread.h>
// The declaration
class CThread : public wxThread {
public:
    CThread() = default;
    ~CThread() = default;
    void *Entry();
};

// The definition
void* CThread::Entry() {
    const int maximum = 1000000;
    for (unsigned int i = 0; i <= maximum; i++) {
        if (i == maximum) {
            wxLogMessage("The counter is finished.");
        }
    }
    return 0;
}

// Main function
wxThread *thread = new CThread();
thread->Create();
thread->Run();

The previous example is a very simple example to use threads and that's what I want.
The ambiguous thing in that example doesn't take any time to be executed, and I don't know if that example is correct or not.

Is that code correct or there's something I missed?

Lion King
  • 32,851
  • 25
  • 81
  • 143
  • 2
    Correct multithreading is **hard**. There are many ways your code sample could be used correctly or incorrectly. If you want to write multithreaded code, I strongly recommend [reading a good book on the topic](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Drew Dormann May 05 '18 at 17:30
  • Your compiler may optimize `Entry()` to just call `wxLogMessage` immediately. Since doing 1000000 comparisons that are known to be false is equivalent to doing nothing. – Drew Dormann May 05 '18 at 17:34
  • Take a look at the sample "thread" provided with wxWidgets installation. – Ripi2 May 05 '18 at 18:26
  • @Ripi2: I have seen this [subject](http://docs.wxwidgets.org/3.0.4/classwx_thread.html), but I think it's not simple enough, and for that, I didn't understand it. – Lion King May 05 '18 at 18:30
  • wxWidgets docs are something that you must be aware of. But they are not a tutorial. As @DrewDormann said, start with a good book or tutorial (not needed to be wx related, just C++) to understand the concepts you need. – Ripi2 May 05 '18 at 18:34
  • Correct multithreading is hard. It is especially so in a GUI program ( e.g. wxwidgets ) because the GUI event handling will become confused with your multithreading. If you want to learn multithreading, start with a simple C++ console program. – ravenspoint May 05 '18 at 19:34

0 Answers0