www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How do I send a HANDLE type to other threads via spawn?

reply Andrej Mitrovic <andrej.mitrovich gmail.com> writes:
HANDLE is defined as:
typedef void* HANDLE;

This is an opaque internal WinAPI type (signed integer) and doesn't
change when spawning new threads.

I can't send this to a background thread via send() since typedef
creates a new type. And I can't send it as an int*, send will normally
complain (I know why). I'd like to avoid using globals if possible.

A snippet of what I'm doing would be (and this is pseudocode):

void workThreadFoo()
{
    // do some work
    // ..
    SendMessage(handleToWindow, SomeEnum.RequestDialogBox);
}

void mainThread()
{
    // create a GUI window, start the window procedure..
}

void windowProc(HANDLE windowHandle, MSG message)
{
    static Tid workThread;
   switch (message)
       case WindowCreated:
             // Now either assign a __gshared global handleToWindow
(my current workaround)
             handleToWindow = windowHandle
             workThread = spawn(&workThreadFoo);

             // Or my preferred but not working way would be:
             workThread = spawn(&workThreadFoo);
             workThread.send(handleToWindow);

       case SomeEnum.RequestDialogBox:
            // create a dialog box
}

Then workThreadFoo uses the handleToWindow handle when calling
SendMessage. I'd really like to remove globals from my code when
possible.

The reason I don't like globals is I've already had a threading bug
where I've accidentally called the wrong thread when sending some
data. Essentially my bug was this:
__gshared Tid mainThread;
__gshared Tid workThread;

workThreadFoo()
{
    workThread.send("some data for mainThread");  // woops, I meant to
call mainThread.send!
}

The more I localize variables, the better.
Jun 29 2011
parent bearophile <bearophileHUGS lycos.com> writes:
Andrej Mitrovic:

 HANDLE is defined as:
 typedef void* HANDLE;
...
 I can't send this to a background thread via send() since typedef
 creates a new type.

typedef is deprecated in D2. Try using an alias. Bye, bearophile
Jun 29 2011