How to pass message to a thread
I need to write a sort of proxy server and my design is a little like this: 1. Socket server (using Windows Event select model). program has a listener thread listenimng for network events.
2. list of clients (currently indexed by socketid). 3. socket server accepts a new connection and then creates a new thread for each client. The new thread creates a socket connection to end destination server (want a persistent connection).I have already written the socket server and that works fine. My problem is as new messages come in from clients, how do I pass this message onto the relevant thread (so message can be sent onto to destination server).
In my server I get the address of the final destination server from the client message. I can lookup the client socket from the list of client sockets. But how do I then send the message to the correct thread?
In the threading I have worked with so far, the thread function just runs a loop. Do I call the thread function, passing it the message as a parameter?
Anyone got any good ideas on how to do this?
Could I not just have a map of client socket id and destination server socket id.
After开发者_如何学运维 accept on a client socket, connect to destination server and send msg. Save destination server socket id to the map.
Thenceforth, when get a new msg from client, lookup dest server in map and send message to requisite server socket.
Actually, do I need to make this multi-threaded?
Use a messaging or synchronization primitive, such as a queue, mailbox, event signal, etc.
For instance, if each thread has a queue for data to send, you would simply write to this queue. The queue must be thread safe to allow concurrent access.
I am going to make an assumption that each client requires the same processing. So all you need is a bunch of worker threads. Get a connection. Pick up the relevant data (mutex). Process. Fire off the response.
So why a thread for each client. Construct a worker thread when required. Seems a simpler solution.
Essentially, you need a message queue for each thread. You can then post the incoming data onto this queue, and the thread can process it in turn.
There are lots of ways of implementing such a queue. You could, for example, use the Windows message queue, and post a Windows message to a window owned by the target thread. Alternatively, you could use a custom thread-safe message queue to pass the data, with the data structure protected by a mutex.
精彩评论