IODispatcher.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /*
  2. * Copyright: JessMA Open Source (ldcsaa@gmail.com)
  3. *
  4. * Author : Bruce Liang
  5. * Website : https://github.com/ldcsaa
  6. * Project : https://github.com/ldcsaa/HP-Socket
  7. * Blog : http://www.cnblogs.com/ldcsaa
  8. * Wiki : http://www.oschina.net/p/hp-socket
  9. * QQ Group : 44636872, 75375912
  10. *
  11. * Licensed under the Apache License, Version 2.0 (the "License");
  12. * you may not use this file except in compliance with the License.
  13. * You may obtain a copy of the License at
  14. *
  15. * http://www.apache.org/licenses/LICENSE-2.0
  16. *
  17. * Unless required by applicable law or agreed to in writing, software
  18. * distributed under the License is distributed on an "AS IS" BASIS,
  19. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. * See the License for the specific language governing permissions and
  21. * limitations under the License.
  22. */
  23. #include "IODispatcher.h"
  24. #include "FuncHelper.h"
  25. #include <signal.h>
  26. #include <pthread.h>
  27. volatile UINT CIODispatcher::sm_uiNum = MAXUINT;
  28. LPCTSTR CIODispatcher::WORKER_THREAD_PREFIX = _T("io-disp-");
  29. BOOL CIODispatcher::Start(IIOHandler* pHandler, int iWorkerMaxEvents, int iWorkers)
  30. {
  31. ASSERT_CHECK_EINVAL(pHandler && iWorkerMaxEvents >= 0 && iWorkers >= 0);
  32. CHECK_ERROR(!HasStarted(), ERROR_INVALID_STATE);
  33. if(iWorkerMaxEvents == 0) iWorkerMaxEvents = DEF_WORKER_MAX_EVENTS;
  34. if(iWorkers == 0) iWorkers = DEFAULT_WORKER_THREAD_COUNT;
  35. m_iMaxEvents = iWorkerMaxEvents;
  36. m_iWorkers = iWorkers;
  37. m_pHandler = pHandler;
  38. m_evExit = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC | EFD_SEMAPHORE);
  39. if(IS_INVALID_FD(m_evExit))
  40. goto START_ERROR;
  41. m_pContexts = make_unique<TDispContext[]>(m_iWorkers);
  42. for(int i = 0; i < m_iWorkers; i++)
  43. {
  44. TDispContext& ctx = m_pContexts[i];
  45. ctx.m_iIndex = i;
  46. ctx.m_epoll = epoll_create1(EPOLL_CLOEXEC);
  47. CHECK_ERROR_FD(ctx.m_epoll);
  48. ctx.m_evCmd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
  49. if(IS_INVALID_FD(ctx.m_evCmd))
  50. goto START_ERROR;
  51. if(!VERIFY(AddFD(i, ctx.m_evCmd, EPOLLIN | EPOLLET, &ctx.m_evCmd)))
  52. goto START_ERROR;
  53. if(!VERIFY(AddFD(i, m_evExit, EPOLLIN, &m_evExit)))
  54. goto START_ERROR;
  55. sigset_t ss;
  56. sigemptyset(&ss);
  57. sigaddset(&ss, SIGPIPE);
  58. VERIFY_IS_NO_ERROR(pthread_sigmask(SIG_BLOCK, &ss, nullptr));
  59. ctx.m_pWorker = make_unique<CWorkerThread>();
  60. if(!VERIFY(ctx.m_pWorker->Start(this, &CIODispatcher::WorkerProc, &ctx)))
  61. goto START_ERROR;
  62. }
  63. return TRUE;
  64. START_ERROR:
  65. EXECUTE_RESTORE_ERROR(Stop(FALSE));
  66. return FALSE;
  67. }
  68. BOOL CIODispatcher::Stop(BOOL bCheck)
  69. {
  70. if(bCheck) CHECK_ERROR(HasStarted(), ERROR_INVALID_STATE);
  71. BOOL isOK = TRUE;
  72. if(m_pContexts)
  73. {
  74. isOK &= IS_NO_ERROR(eventfd_write(m_evExit, m_iWorkers));
  75. for(int i = 0; i < m_iWorkers; i++)
  76. {
  77. TDispContext& ctx = m_pContexts[i];
  78. if(ctx.m_pWorker)
  79. isOK &= ctx.m_pWorker->Join();
  80. if(!ctx.m_queue.IsEmpty())
  81. {
  82. TDispCommand* pCmd = nullptr;
  83. while(ctx.m_queue.PopFront(&pCmd))
  84. TDispCommand::Destruct(pCmd);
  85. VERIFY(ctx.m_queue.IsEmpty());
  86. }
  87. if(IS_VALID_FD(ctx.m_evCmd))
  88. isOK &= IS_NO_ERROR(close(ctx.m_evCmd));
  89. if(IS_VALID_FD(ctx.m_epoll))
  90. isOK &= IS_NO_ERROR(close(ctx.m_epoll));
  91. }
  92. }
  93. if(IS_VALID_FD(m_evExit))
  94. isOK &= IS_NO_ERROR(close(m_evExit));
  95. Reset();
  96. return isOK;
  97. }
  98. VOID CIODispatcher::Reset()
  99. {
  100. m_uiSeq = MAXUINT;
  101. m_iWorkers = 0;
  102. m_iMaxEvents= 0;
  103. m_evExit = INVALID_FD;
  104. m_pHandler = nullptr;
  105. m_pContexts = nullptr;
  106. }
  107. VOID CIODispatcher::MakePrefix()
  108. {
  109. UINT uiNumber = ::InterlockedIncrement(&sm_uiNum);
  110. m_strPrefix.Format(_T("%s%u-"), WORKER_THREAD_PREFIX, uiNumber);
  111. }
  112. TDispContext& CIODispatcher::GetContext(int idx, FD fd)
  113. {
  114. if(idx < 0) idx = fd;
  115. ASSERT(idx >= 0);
  116. if(idx >= m_iWorkers) idx %= m_iWorkers;
  117. return m_pContexts[idx];
  118. }
  119. BOOL CIODispatcher::SendCommandByIndex(int idx, USHORT t, UINT_PTR wp, UINT_PTR lp)
  120. {
  121. return SendCommandByIndex(idx, TDispCommand::Construct(t, wp, lp));
  122. }
  123. BOOL CIODispatcher::SendCommandByIndex(int idx, TDispCommand* pCmd)
  124. {
  125. TDispContext& ctx = GetContextByIndex(idx);
  126. return SendCommand(ctx, pCmd);
  127. }
  128. BOOL CIODispatcher::SendCommandByFD(FD fd, USHORT t, UINT_PTR wp, UINT_PTR lp)
  129. {
  130. return SendCommandByFD(fd, TDispCommand::Construct(t, wp, lp));
  131. }
  132. BOOL CIODispatcher::SendCommandByFD(FD fd, TDispCommand* pCmd)
  133. {
  134. TDispContext& ctx = GetContextByFD(fd);
  135. return SendCommand(ctx, pCmd);
  136. }
  137. BOOL CIODispatcher::SendCommand(TDispContext& ctx, TDispCommand* pCmd)
  138. {
  139. ctx.m_queue.PushBack(pCmd);
  140. return VERIFY_IS_NO_ERROR(eventfd_write(ctx.m_evCmd, 1));
  141. }
  142. BOOL CIODispatcher::CtlFD(int idx, FD fd, int op, UINT mask, PVOID pv)
  143. {
  144. const TDispContext& ctx = GetContext(idx, fd);
  145. epoll_event evt = {mask, pv};
  146. return IS_NO_ERROR(epoll_ctl(ctx.m_epoll, op, fd, &evt));
  147. }
  148. int CIODispatcher::WorkerProc(TDispContext* pContext)
  149. {
  150. ::SetSequenceThreadName(SELF_THREAD_ID, m_strPrefix, m_uiSeq);
  151. m_pHandler->OnDispatchThreadStart(SELF_THREAD_ID);
  152. BOOL bRun = TRUE;
  153. unique_ptr<epoll_event[]> pEvents = make_unique<epoll_event[]>(m_iMaxEvents);
  154. while(bRun)
  155. {
  156. int rs = NO_EINTR_INT(epoll_pwait(pContext->m_epoll, pEvents.get(), m_iMaxEvents, INFINITE, nullptr));
  157. if(rs <= TIMEOUT)
  158. ERROR_ABORT();
  159. for(int i = 0; i < rs; i++)
  160. {
  161. UINT events = pEvents[i].events;
  162. PVOID ptr = pEvents[i].data.ptr;
  163. if(ptr == &pContext->m_evCmd)
  164. ProcessCommand(pContext, events);
  165. else if(ptr == &m_evExit)
  166. bRun = ProcessExit(pContext, events);
  167. else
  168. ProcessIo(pContext, ptr, events);
  169. }
  170. }
  171. m_pHandler->OnDispatchThreadEnd(SELF_THREAD_ID);
  172. return 0;
  173. }
  174. BOOL CIODispatcher::ProcessCommand(TDispContext* pContext, UINT events)
  175. {
  176. if(events & _EPOLL_ALL_ERROR_EVENTS)
  177. ERROR_ABORT();
  178. if(!(events & EPOLLIN))
  179. return FALSE;
  180. BOOL isOK = TRUE;
  181. eventfd_t v;
  182. int rs = eventfd_read(pContext->m_evCmd, &v);
  183. if(IS_NO_ERROR(rs))
  184. {
  185. ASSERT(v > 0);
  186. TDispCommand* pCmd = nullptr;
  187. while(pContext->m_queue.PopFront(&pCmd))
  188. {
  189. m_pHandler->OnCommand(pContext, pCmd);
  190. TDispCommand::Destruct(pCmd);
  191. }
  192. }
  193. else if(IS_HAS_ERROR(rs))
  194. {
  195. ASSERT(IS_WOULDBLOCK_ERROR());
  196. isOK = FALSE;
  197. }
  198. return isOK;
  199. }
  200. BOOL CIODispatcher::ProcessExit(const TDispContext* pContext, UINT events)
  201. {
  202. if(events & _EPOLL_ALL_ERROR_EVENTS)
  203. ERROR_ABORT();
  204. if(!(events & EPOLLIN))
  205. return TRUE;
  206. BOOL bRun = TRUE;
  207. eventfd_t v;
  208. int rs = eventfd_read(m_evExit, &v);
  209. if(IS_HAS_ERROR(rs))
  210. ASSERT(IS_WOULDBLOCK_ERROR());
  211. else
  212. {
  213. ASSERT(v == 1);
  214. bRun = FALSE;
  215. }
  216. return bRun;
  217. }
  218. BOOL CIODispatcher::ProcessIo(const TDispContext* pContext, PVOID pv, UINT events)
  219. {
  220. if(!m_pHandler->OnBeforeProcessIo(pContext, pv, events))
  221. return FALSE;
  222. BOOL rs = DoProcessIo(pContext, pv, events);
  223. m_pHandler->OnAfterProcessIo(pContext, pv, events, rs);
  224. return rs;
  225. }
  226. BOOL CIODispatcher::DoProcessIo(const TDispContext* pContext, PVOID pv, UINT events)
  227. {
  228. if(events & EPOLLERR)
  229. return m_pHandler->OnError(pContext, pv, events);
  230. if((events & EPOLLPRI) && !m_pHandler->OnReadyPrivilege(pContext, pv, events))
  231. return FALSE;
  232. if((events & EPOLLIN) && !m_pHandler->OnReadyRead(pContext, pv, events))
  233. return FALSE;
  234. if((events & EPOLLOUT) && !m_pHandler->OnReadyWrite(pContext, pv, events))
  235. return FALSE;
  236. if((events & (_EPOLL_HUNGUP_EVENTS)) && !m_pHandler->OnHungUp(pContext, pv, events))
  237. return FALSE;
  238. return TRUE;
  239. }
  240. FD CIODispatcher::AddTimer(int idx, LLONG llInterval, PVOID pv)
  241. {
  242. FD fdTimer = ::CreateTimer(llInterval);
  243. if(IS_VALID_FD(fdTimer))
  244. {
  245. if(!AddFD(idx, fdTimer, EPOLLIN | EPOLLET, pv))
  246. {
  247. close(fdTimer);
  248. fdTimer = INVALID_FD;
  249. }
  250. }
  251. return fdTimer;
  252. }
  253. BOOL CIODispatcher::DelTimer(int idx, FD fdTimer)
  254. {
  255. BOOL isOK = FALSE;
  256. if(IS_VALID_FD(fdTimer))
  257. {
  258. if(DelFD(idx, fdTimer))
  259. isOK = TRUE;
  260. close(fdTimer);
  261. }
  262. return isOK;
  263. }