@bridget99 said:
@darren71 said:
How does he expect you to callback to the original thread? The only way to achieve this is for the original thread to poll it constantly waiting for an answer. If this was the norm it would make threading usless to essentially block one while waiting.
I don't know exactly what the OP's maligned coworker had in mind. But the most obvious way to take a callback function and force its execution into the "correct" thread in Windows is to post a message. Many threads are "pumping" a message queue in Windows anyway.... yes, this does involve a form of polling. Consider the cannonical Windows message loop:
while(GetMessage(&Msg, NULL, 0, 0) > 0)
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}GetMessage() will sit in a loop periodically checking (i.e. polling) for a message until one arrives.
This seems inefficient, but so many Windows threads will need to be doing this anyway. The "main" thread of any app with a GUI will constantly be running this loop, as will any apartment-threaded COM objects running in a "free" caller thread. So, relying on such a loop is not bad... it's just a part of the Windows infrastructure, at a fairly low (i.e. fast) level. Relying on these loops is the best synchronization architecture in many cases. Message passing eliminates a whole category of errors, e.g. race conditions occuring in the execution of out-of-thread callbacks.
You are right to worry about the possibility of multithreading-without-parallel-execution, which is more common than people realize. But in this case, I think that there is still real parallelism in the system. The "original" thread can make a call that will eventually result in a callback, and then continue doing other things. The callback function can simply post the message without waiting for its analysis by the original thread, by using a call to PostMessage().
I stand by my original analysis that the "stupidity" in this case is really just good advice... any multithreaded process needs to be synchronized and message-passing is a good approach.
This is fine if we were talking about an application that had a message pump. In this case, we are talking about an API that talks to our back-end servers to receive prices. Him, the consumer of the API does have the ability to post it back to the main thread and I suspect this is what he did to overcome his issue.
The API in question takes the packet of data received over a socket and calls a user defined callback. The callback itself is not threaded and as such until the callback completes there is no need for the API itself to worry about how the consumer of the data will use it.
Again, I suspect that he did post back and that is a requirement of his application. My real issue was his demanding that I call the user-defined callback back on his main thread. As I am the developer of the API, I do not feel it is my responsibility to modify my code to adhere to his development standard.