问题
The network lib I'm writing needs to send and receive messages through a TCP socket. Messages can be sent or received any time, i.e should work as a full duplex channel.
I was able to implement such scenario using two threads: main thread calling send() and a dedicated thread mostly blocked at recv() call.
My question is: is it possible to implement the same scenario with a single thread? I.e. by registering some callback function?
As a side note: I need implement this scenario in C++, Java and Python.
回答1:
Yes, it possible. You need to use an API that allows multiplexed I/O. Under C/C++ and Python you can use select() and non-blocking I/O, so that the only networking call you ever block in is select(). There is also poll() and epoll() and a number of other similar APIs that accomplish the same thing, with varying degrees of efficiency and portability. Java has non-blocking I/O APIs also.
Another possibility is to use asynchronous I/O, where you tell the OS to start an I/O transaction and it notifies you (by some mechanism) when it has finished the operation. I'm not familiar with that style of network programming, however, so I won't try to give details.
回答2:
In general, a library would do this by providing an interface into the application's main loop / event loop.
For example, most single-threaded network-using applications would have a main loop that blocks in select()
, poll()
or similar. Your library would just return a file descriptor that the application should include in its select()
/ poll()
call, and a callback function that the application should call when that file descriptor is readable.
来源:https://stackoverflow.com/questions/4675824/how-to-implement-a-full-duplex-channel-over-tcp-with-a-single-thread