其实这四个名词在概念上有一些微妙的差别,
Sync/Async IO的差别在于程式是否要去等待OS的IO操作结束:在boost中是指io_service选用了run()或者是poll(),会进行kernel context switch到OS kernel来运行。
而Blocking/Non-Blocking则是指我们是否要等待程式执行流程中的IO结束才能继续执行,主要是由application来实作、设计执行的机制。
其实一个程式是不是Sync/Asyn或blocking/non-blocking,其实看的是一段程式码或者是一个function
通常如果该段程式码包含while回圈来判断某个档案是状态,那么就是blocking,但如果这时候又程式thread来分配该任务的执行,那么就是non-blocking。
在non-blocking的程式中,如果有牵扯到档案的读写问题,那么我们就必须在程式中撰写一些机制去确认该档案是如已经可以写入,以必免造成race condition的情况。通常依照不同的作业系统会使用poll、select、epoll、iocp等机制。
在boost::ASIO中,由于为了要达成跨平台,因此在背后实作了Proactor模式来隐藏细节,并以Reactor来实作不同平台的机制。我们可以利用以下的程式码印出我们的作业系统所采用的是那一种:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
#include <iostream>
#include <string>
#include <boost /asio.hpp>
int main ( )
{
std :: string output ;
#if defined(BOOST_ASIO_HAS_IOCP)
output = "iocp" ;
#elif defined(BOOST_ASIO_HAS_EPOLL)
output = "epoll" ;
#elif defined(BOOST_ASIO_HAS_KQUEUE)
output = "kqueue" ;
#elif defined(BOOST_ASIO_HAS_DEV_POLL)
output = "/dev/poll" ;
#else
output = "select" ;
#endif
std :: cout < < output << std :: endl ;
} |