Normal IOCP 的使用

本文介绍Windows下的IO完成端口(IOCP)机制实现,包括创建IOCP、关联句柄、投递异步操作及等待完成等步骤。适用于需要了解底层I/O模型或多路复用技术的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
 
1、创建IOCP
ACE_WIN32_Proactor::ACE_WIN32_Proactor (size_t number_of_threads,
                                        int used_with_reactor_event_loop)
 : completion_port_ (0),
    // This *MUST* be 0, *NOT* ACE_INVALID_HANDLE !!!
    number_of_threads_ (static_cast<DWORD> (number_of_threads)),
    used_with_reactor_event_loop_ (used_with_reactor_event_loop)
{
 // Create the completion port.
 this->completion_port_ = ::CreateIoCompletionPort (INVALID_HANDLE_VALUE,
                                                     0,
                                                     0,
                                                     this->number_of_threads_);
//...
}
2、将一个句柄同完成端口关联到一起
int
ACE_WIN32_Proactor::register_handle (ACE_HANDLE handle,
                                     const void *completion_key)
{
#if defined (_MSC_VER) && (_MSC_VER < 1300)
 ULONG comp_key (reinterpret_cast<ULONG> (completion_key));
#else
  ULONG_PTR comp_key (reinterpret_cast<ULONG_PTR> (completion_key));
#endif
 
 // No locking is needed here as no state changes.
 ACE_HANDLE cp = ::CreateIoCompletionPort (handle,
                                            this->completion_port_,
                                            comp_key,
                                            this->number_of_threads_);
//...
}
 
 
 
3、投递一个(或多个)异步操作
4、在完成端口上等待

int

ACE_WIN32_Proactor::handle_events (unsigned long milli_seconds)

{

  ACE_OVERLAPPED *overlapped = 0;

  u_long bytes_transferred = 0;

#if defined (_MSC_VER) && (_MSC_VER < 1300)

  ULONG completion_key = 0;

#else

  ULONG_PTR completion_key = 0;

#endif

 

  // Get the next asynchronous operation that completes

  BOOL result = ::GetQueuedCompletionStatus (this->completion_port_,

                                             &bytes_transferred,

                                             &completion_key,

                                             &overlapped,

                                             milli_seconds);

//Check errors

 

//Execute the completion handler

    this->application_specific_code (asynch_result,

                                       static_cast<size_t> (bytes_transferred),

                                       (void *) completion_key,

                                       result_err);

  return 1;

}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值