开发者

How to implement asynchronous write in c/c++?

WriteFile( tmp_pipe, &Time, sizeof(double), &dwWritten, NULL );

The above is synchronous, if buffer of tmp_pipe is used up, it'll wait there.

H开发者_如何学Cow to make the above finish instantly, maybe just ignore the data if the buffer is full?


The definitive way is to use boost::asio.

Asynchronous IO is very difficult to get right and portable if you don't use a good library.


If you don't need portable code then using Win32 directly is fine.

If you specify the address of an OVERLAPPED structure as the final parameter then you will get info about the async write later via that OVERLAPPED structure. You need to have opened the file in overlapped mode. Alternatively, you can use WriteFileEx and provide a completion callback. Read the MSDN docs for more details.

Note that you still have to handle sensibly the case where you have I/O outstanding on the pipe. There is no way to just do 'fire-and-forget' writes, ignoring the fact that the pipe has finite bandwidth. Eventually you will hit some kernel buffer pool limit and an I/O will fail, possibly breaking your pipe until it's restarted.

This is hard to get right but there are plenty of samples online to help. For extra credit, use I/O Completion ports which offer the highest-performance for async I/O on user-mode Windows. Not 100% sure that this applies to pipes, but certainly for sockets and files.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜