Is it possible to have the same socket spread over two theads? IE having one thread doing a recv( ) on the socket, whilst the other one does a send( )? I looked into select( ), but I want something less CPU-intensive.
Printable View
Is it possible to have the same socket spread over two theads? IE having one thread doing a recv( ) on the socket, whilst the other one does a send( )? I looked into select( ), but I want something less CPU-intensive.
Well, in a way, that really doesn't make much sense to do that way. After all, the request-reply cycle is pretty much like wheels turning, that is, they should follow eachother. Of course, there may be times where this would be desirable. Is it safe, though? I'm not so sure. It seems a little dangerous. Imagine doing reading/writing from the same file in separate threads. Kind of sketchy business! Probably a more kosher thing to do would be to launch each socket into it's own thread, meaning you could serve multiple sockets while still maintaining a sense syncronicity by reading/writing from the same thread.
What I'm doing is a client-server chat program. I don't want the server to wait for the client to send data before it can send information to the client.
select() is not cpu intensive. i wrote a chat server (im making usernames and whatnot improvements now) that uses select() and cpu usage stays at 0%.
You used it in an infinite loop?
You may want to see Is Winsock thread-safe? from the Winsock Programmer's FAQ for an answer to your original question.
Guess I'll just stick with select then, since send( ) and recv( ) on the same socket simultaneously is a grey area.
yes i used it in an infinite loop.
if you notice the processor usage goes up, then you made a mistake somewhere. it should work unnoticably.
The point of select is so you do not have to do constant polling on the socket, not to mention you can check a whole set of sockets at once instead of one at a time. It is not CPU intensive, assuming you use it correctly. Threads are rarley the answer to the question, I would say. You would need to set up some sort of concurrency if you wanted one socket on multiple threads, so you would not gain anything from multithreading your application.
I totally disagree, orbitz. There really isn't much advantage to running sockets from the main thread, since that ties up the user interface too much, even using select(). From that standpoint, *at least* one thread is absolutely necessary, and especially so (obviously) if you are using blocking sockets. My weapons of choice would be blocking sockets launched into individual threads.