win32: waitable event object for GUI messages? - multithreading

Is it possible to create an event object that becomes signalled when GUI message(s) is/are available, like one can create event objects that signal the presence of data on a socket for instance? The idea would be to use a WaitMultipleEvents for either something happening on the GUI or a request arriving on a TCP/IP socket.
I'd delegate the whole client/server comm stuff to a background thread if this weren't a QuickTime app (QuickTime is rather quirky where multithreading is concerned, on win32 at least).
BTW, can one do things like moving/resizing/renaming windows created on another thread, using the dedicated functions - or would that require posting messages explicitly?

There's no waitable object for messages in your queue, but there is a wait function that will wait for a waitable object or a message in your queue. See MsgWaitForMultipleObjects.

There is no such event to signal that a Windows message is available. The solution is to get socket notifications in the form of a Windows message instead of an event. WSAAsyncSelect configures this mode in the socket. This let you use your message loop to get both GUI messages and socket notifications, all in one thread.

Thanks for your answers. Indeed, I was reminded elsewhere of MsgWaitForMultipleObjects, and use that (code extract:)

Related

ZMQ poll and send at the same time from different threads

I have a program that uses ZMQ to send and receive between a C++ application and a Python GUI. The Python sends all commands to the C++ app to do the work, the C++ app periodically sends back status to update the GUI.
The C++ is multi-theaded but we never made the call zmq_send thread safe, so in 1 out of 100,000 runs we'd get an unhandled exception or segmentation fault if two threads tried to send status back to the gui simultaneously. This took longer than I care to admit figuring out since it was so sporadic. This was easily solved with a mutex around zmq_send because the socket is managed by a singleton.
In addition to the processing threads, there is one thread that just idly waits to receive and dispatch commands from the gui using zmq_poll and then zmq_msg_recv when something is available.
The question, can I safely poll the same socket while a send is happening? Most of the time the receive thread is sitting in zmq_poll with a timeout, and sends seem to be happening without issue. I can't seem to find any good documentation about this. I assume a mutex needs to protect zmq_send and zmq_msg_recv from occurring simultaneously, but I am not sure about the safety of polling while sending.
Details about the setup: using PAIR interface with a single client and server. All messages are small (<1KB). There is only one socket shared for sending and receiving.
This is a large, decade old application I'd like to avoid redesigning if possible.

Can I send() from one thread and recv() from another on the same ZeroMQ REQ/REP Socket?

As the documents say, ZMQ sockets are not thread-safe. So I assume the answer to the title is 'No'.
Still, I can't figure out how to implement a non-blocking request-reply pattern using ZMQ:
Specifically, the client has a main thread which goes on about its business processing messages from a (thread-safe) message queue. The messages come from various sources, such as network, timers, I/O etc.
Occasionally the main thread wishes to send a request to a remote server, but it does not want to wait for a response (which may take a while to arrive).
Normally, I would use two threads:
The main message-processing loop thread. This will send() request on the REQ/REP socket
An auxiliary listener thread which will wait for the response from the server. This will use a blocking recv() on the socket, and push the responses to the main thread's queue.
How would I achieve this using ZeroMQ? Should the auxilary thread open an inproc socket and listen to messages from the main thread?
Actually, single thread is enough. Just send request to the server and poll messages with zmq_poll().
This model is fine if one request at a time is suffucient. If you need so send multiple requests and read replies asynchronously, use DEALER socket instead of REQ. Just send some requestId as the first frame, then add empty delimiter frame, then send actual request.
Chapter 3 of the guide has more details about REQ/REP message envelopes: http://zguide.zeromq.org/php:chapter3
Please let me know if this isn't clear enough, I will probably extend my answer with few code samples.

winsock application and multhreading - listening to socket event from another thread

assume we have an application which uses winsock to implement tcp communication.
for each socket we create a thread and block-receiving on it.
when data arrives, we would like to notify other threads (listening threads).
i was wondering what is the best way to implement this:
move away from this design and use a non-blocking socket, then the listening thread will have to iterate constantly and call a non-blocking receive, thus making it thread safe (no extra threads for the sockets)
use asynchronous procedure calls to notify listening threads - which again will have to alert-wait for apc to queue for them.
implement some thread safe message queue, where each socket thread will post messages to it, and the listener, again, will go over it every interval and pull data from it.
also, i read about WSAAsyncSelect, but i saw that this is used to send messages to a window. isnt there something similar for other threads? (well i guess apcs are...)
Thanks!
Use I/O completion ports. See the CreateIoCompletionPort() and the GetQueuedCompletionStatus() functions of the Win32 API (under File Management functions). In this instance, the socket descriptors are used in place of file handles.
You'll always be better off abstracting the mechanics of socket API (listening, accepting, reading & writing) in a separate layer from the application logic. Have an object that captures the state of a connection, which is created during an incoming connection and you can maintain buffers in this object for the incoming and outgoing traffic. This will allow your network interface layer to be independent of the application code. This will also make the code cleaner by separating the application functionality from the underlying communication mechanism.
Blocking or non-blocking socket decision depends on the level of scalability that your applications needs to achieve. If your application needs to support hundreds of incoming connections, adopting a thread-per-socket approach is not going to be very wise. You'll be better off going for an Io ports based implementation, which will make your app immensely scaleable at added code complexity. However, if you only foresee a few 10s of connections at any point in time, you can go for an asynchronous sockets model using Win32 events or messages. Win32 events based approach doesn't scale very well beyond a certain limit as you would have to manage multiple threads if the number of concurrent sockets exceed 63 (as WaitForMultipleObjects can only support a max of 64 sockets). Windows message based mechanism doesn't have this limitation though. OHOH, Win32 event based approach does not require a GUI window to work.
Check out WSAEventSelect along with WSAAsyncSelect API documentation in MSDN.
You might want to take a look at boost::asio package as well. It provides a neat (though a little complex) C++ abstraction over sockets API.

How can I push a TWSocket's OnDataAvailable() event to a background thread in my Delphi 6 application?

I have a Delphi 6 application that uses the ICS component suite to do socket communications. I have my own server socket VCL component that creates client TWSocket sockets when a new session becomes available. The client sockets I create do have the Multithreaded property set to TRUE, but all that does is changes the way the client socket handles socket messages to a manner that is safe from a background thread (non-main VCL thread). TWSocket does not spawn a thread to handle socket data traffic, which is what I need.
I need to have the receive calls occur off the main VCL thread, the main user interface thread, because the incoming data to the client socket is audio data that needs to be processed rapidly, in 50-100 milliseconds or less. In other words, one hiccup on the main VCL thread and the audio stream is disrupted. This is why I want to push the OnDataAvailable() event that fires whenever incoming data is available on to a high priority background thread. In other words, I want to force the message processing loop belonging to the client TWSocket object to a background thread.
I believe I can do this by creating the client socket via a background thread, but I'm hoping to avoid that since currently I use a VCL component I made that acts as a socket server. This is the entity that Accepts the incoming connection and spawns the client sockets. The socket server is created on the main VCL thread.
Therefore my question is, is there a (relatively) easy way to create the client sockets so they use an existing background thread to do their socket processing, especially the FD_RECV message handling? If not an existing background thread, then I will create one for each client socket I create, but I need to know how to make sure the new TWSocket object uses that background thread when it runs its message loop that processes socket messages, so how would I do that?
For other ICS/TWSocket users out there, the solution is in the ICS ThrdSrv demonstration project that comes with the package. Take a close look at that project, especially its use of the ThreadAttach() and ThreadDetach() methods. That sample project shows how to create client sockets that have message pumps that run in the context of a worker thread.

Creating a simple Linux API

I have a simple application on a OpenWRT style router. It's written in C++ currently. The router (embedded Linux) has very limited disk space and RAM. For example there is not enough space to install Python.
So, I want to control this daemon app via the network. I have read some tutorials on creating sockets, and listening to the port for activity. But I haven't been able to integrate the flow into a C++ class. And I haven't been able to figure out how to decode the information received, or how to send a response.
All the tutorials I've read are dead ends, they show you how to make a server that basically just blocks until it receives something, and then returns a message when it got something.
Is there something a little more higher level that can be used for this sort of thing?
Sounds like what you are asking is "how do I build a simple network service that will accept requests from clients and do something in response?" There are a bunch of parts to this -- how do you build a service framework, how do you encode and decode the requests, how do you process the requests and how do you tie it all together?
It sounds like you're having problems with the first and last parts. There are two basic ways of organizing a simple service like this -- the thread approach and the event approach.
In the thread approach, you create a thread for each incoming connection. That thread reads the messages (requests) from that connection (file descriptor), processes them, and writes back responses. When a connection goes away, the thread exits. You have a main 'listening' thread that accepts incoming connections and creates new threads to handle each one.
In the event approach, each incoming request becomes an event. You then have event handlers that processes these events, sending back responses. Its important that the event handlers NOT block and complete promptly, otherwise the service may appear to lock up. Your program has a main event loop that waits for incoming events (generally blocking on a single poll or select call) and reads and dispatches each event as appropriate.
I installed python-mini package with opkg, which has socket and thread support.
Works like a charm on a WRT160NL with backfire/10.03.1.

Resources