Lit Window Productions

Products
Shop
Knowhow
wxHowto
Intellisense
wxDoxygen
wxSocket
HowTo
Library
About

RSS Feed
Whats this?

Contact
Privacy

Fast, easy dialog editing and code generation with Anthemionís Dialog Editor for wxWidgets...

Howto: Using wxSocket in a secondary thread.

If you have tried this, you will have stumbled across the following problem(s):

  • 100% CPU usage by wxWidgets application
  • All socket operations such as Read/Write time out.
  • Things work if you put them in the main thread.

Note: This information is valid for wxMSW (Microsoft Windows Platforms).

wxVisualSetup

The easiest way to get Intellisense!

And not just Intellisense: wxVisualSetup includes Integrated wxWidgets Help, a Project Wizard, Intellisense, Dynamic Help and Tips & Tricks for wxWidgets and Microsoft Visual Studio .NET and Visual Studio .NET 2003


$ 39.95 / € 34.44

I have not tested this on Linux or other platforms.

To use wxSockets in a secondary thread, you must

  • call wxSocketBase::Initialize from the main thread before creating any sockets. The best place to do this is in wxApp::OnInit.
  • make sure that the main thread is running always. Do not sleep or use semaphores to block the main thread.

Here is a little background: This is an excerpt from my post on wx-users...

    for wxWidgetsMSW (which also explains the
    odd requirement to call wxSocketBase::Initialize in the main thread):
    When Initialize is called for the first time, it creates a hidden
    window. Socket operations do not block. Instead they use an
    asynchronous model. All internal socket operation will return
    immediately. When a write is completed, the OS will send a windows
    message to the window created by Initialize.

    What happens in your case is:

    a) If you don't call Initialize in the main thread, the window will be
    created in the secondary thread, which under wxWidgets has no message
    loop. The main message loop will only handle windows created in the
    main thread. So the events sent to this window will get lost.

    b) If you do call Initialize in the main thread: When you call Write
    in a secondary thread, the wxWidgets socket code waits in a busy loop.
    It will call write once and then call a 'getstatus' method which loops
    until an internal flag has been set. The code looks somewhat like:

    while (!flag) {
       sleep(0); // give up timeslice
    }

    If you block the main thread with sleep or wxCondition, the event sent
    by the operating system cannot be processed and will never reach the
    hidden socket sink window and so cannot set the flag.

    It is my impression that the socket classes seem to be not very well
    integrated into wxWidgets and - at least in part - not very well
    written. IMHO busy loops really should be avoided.

[Home] [Products] [Shop] [Knowhow] [Library] [About]

© 2004, Hajo Kirchhoff, last modified Mar 06, 2008

back to top