资讯专栏INFORMATION COLUMN

Swoole 源码分析——Server模块之Timer模块与时间轮算法

qieangel2013 / 3244人阅读

摘要:当其就绪时,会调用执行定时函数。进程超时停止进程将要停止时,并不会立刻停止,而是会等待事件循环结束后停止,这时为了防止进程不退出,还设置了的延迟,超过就会停止该进程。当允许空闲时间小于时,统一每隔检测空闲连接。

前言

swooletimer 模块功能有三个:用户定时任务、剔除空闲连接、更新 server 时间。timer 模块的底层有两种,一种是基于 alarm 信号,一种是基于 timefd

timer 数据结构

timer 数据结构是 swTimer。其中 heap 是多个 swTimer_node 类型构成的一个数据堆,该数据堆按照下一次执行时间来排序,下次执行时间离当前时间越近,元素的位置越靠前;mapswTimer_node 类型的 map,其 keyswTimer_node 类型的 id,该数据结构可以通过 id 快速查找对应的 swTimer_node 元素;numswTimer_node 元素个数;use_pipe 标志着 worker 进程中是否使用管道 pipe 来获知 alarm 信号已触发;fd 用于 timefd_current_id 是当前最大 swTimer_nodeid_next_id 就是下一个新建的 swTimer_nodeid 值,是 _current_id + 1;_next_msec 是下次检查定时器的时间。

_swTimer_nodeheap_node_swTimer 中的数据堆元素;data 一般存储 servercallback 是定时器触发后需要执行的回调函数;exec_msec 是该元素应该执行的时间;id 是元素在 swTimer 中的 idtype 有三种:SW_TIMER_TYPE_KERNELserver 内置定时函数)、SW_TIMER_TYPE_CORO(协程定时函数)、SW_TIMER_TYPE_PHP(PHP 定时函数)

</>复制代码

  1. struct _swTimer
  2. {
  3. /*--------------timerfd & signal timer--------------*/
  4. swHeap *heap;
  5. swHashMap *map;
  6. int num;
  7. int use_pipe;
  8. int lasttime;
  9. int fd;
  10. long _next_id;
  11. long _current_id;
  12. long _next_msec;
  13. swPipe pipe;
  14. /*-----------------for EventTimer-------------------*/
  15. struct timeval basetime;
  16. /*--------------------------------------------------*/
  17. int (*set)(swTimer *timer, long exec_msec);
  18. swTimer_node* (*add)(swTimer *timer, int _msec, int persistent, void *data, swTimerCallback callback);
  19. };
  20. struct _swTimer_node
  21. {
  22. swHeap_node *heap_node;
  23. void *data;
  24. swTimerCallback callback;
  25. int64_t exec_msec;
  26. uint32_t interval;
  27. long id;
  28. int type; //0 normal node 1 node for client_coro
  29. uint8_t remove;
  30. };
Timer 定时器 swTimer_init 创建定时器

创建定时器需要给定一个间隔时间,每隔这个时间就要检查 swTimer 中的 _swTimer_node 元素,如果时间已经超过了 _swTimer_node 元素的 exec_msec 时间,就要执行定时函数。

swTimer_now 函数初始化 basetimeswTimer_now 函数可以获取当前时间,使用的是 clock_gettimeCLOCK_MONOTONIC 获取绝对时间,或者使用 gettimeofday 函数

如果是 worker 进程,那么调用 swSystemTimer_init 函数对定时器进行初始化;如果是 master 进程,那么调用 swReactorTimer_init 进行初始化

</>复制代码

  1. int swTimer_now(struct timeval *time)
  2. {
  3. #if defined(SW_USE_MONOTONIC_TIME) && defined(CLOCK_MONOTONIC)
  4. struct timespec _now;
  5. if (clock_gettime(CLOCK_MONOTONIC, &_now) < 0)
  6. {
  7. swSysError("clock_gettime(CLOCK_MONOTONIC) failed.");
  8. return SW_ERR;
  9. }
  10. time->tv_sec = _now.tv_sec;
  11. time->tv_usec = _now.tv_nsec / 1000;
  12. #else
  13. if (gettimeofday(time, NULL) < 0)
  14. {
  15. swSysError("gettimeofday() failed.");
  16. return SW_ERR;
  17. }
  18. #endif
  19. return SW_OK;
  20. }
  21. int swTimer_init(long msec)
  22. {
  23. if (swTimer_now(&SwooleG.timer.basetime) < 0)
  24. {
  25. return SW_ERR;
  26. }
  27. SwooleG.timer.heap = swHeap_new(1024, SW_MIN_HEAP);
  28. if (!SwooleG.timer.heap)
  29. {
  30. return SW_ERR;
  31. }
  32. SwooleG.timer.map = swHashMap_new(SW_HASHMAP_INIT_BUCKET_N, NULL);
  33. if (!SwooleG.timer.map)
  34. {
  35. swHeap_free(SwooleG.timer.heap);
  36. SwooleG.timer.heap = NULL;
  37. return SW_ERR;
  38. }
  39. SwooleG.timer._current_id = -1;
  40. SwooleG.timer._next_msec = msec;
  41. SwooleG.timer._next_id = 1;
  42. SwooleG.timer.add = swTimer_add;
  43. if (swIsTaskWorker())
  44. {
  45. swSystemTimer_init(msec, SwooleG.use_timer_pipe);
  46. }
  47. else
  48. {
  49. swReactorTimer_init(msec);
  50. }
  51. return SW_OK;
  52. }
swReactorTimer_init 初始化

对于 master 进程,只需要设置 main_reactor 的超时时间即可,当发生超时事件之后,main_reactor 会调用 onTimeout 函数;或者一个事件循环最后,会调用 onFinish 函数;这两个函数都会最终调用 swTimer_select,来筛选那些已经到了执行时间的元素。

</>复制代码

  1. static int swReactorTimer_init(long exec_msec)
  2. {
  3. SwooleG.main_reactor->check_timer = SW_TRUE;
  4. SwooleG.main_reactor->timeout_msec = exec_msec;
  5. SwooleG.timer.set = swReactorTimer_set;
  6. SwooleG.timer.fd = -1;
  7. return SW_OK;
  8. }
  9. static int swReactorEpoll_wait(swReactor *reactor, struct timeval *timeo)
  10. {
  11. ...
  12. if (reactor->timeout_msec == 0)
  13. {
  14. if (timeo == NULL)
  15. {
  16. reactor->timeout_msec = -1;
  17. }
  18. else
  19. {
  20. reactor->timeout_msec = timeo->tv_sec * 1000 + timeo->tv_usec / 1000;
  21. }
  22. }
  23. while (reactor->running > 0)
  24. {
  25. msec = reactor->timeout_msec;
  26. n = epoll_wait(epoll_fd, events, max_event_num, msec);
  27. if (n < 0)
  28. {
  29. ...
  30. }
  31. else if (n == 0)
  32. {
  33. if (reactor->onTimeout != NULL)
  34. {
  35. reactor->onTimeout(reactor);
  36. }
  37. continue;
  38. }
  39. ...
  40. if (reactor->onFinish != NULL)
  41. {
  42. reactor->onFinish(reactor);
  43. }
  44. ...
  45. }
  46. ...
  47. }
  48. static void swReactor_onTimeout(swReactor *reactor)
  49. {
  50. swReactor_onTimeout_and_Finish(reactor);
  51. if (reactor->disable_accept)
  52. {
  53. reactor->enable_accept(reactor);
  54. reactor->disable_accept = 0;
  55. }
  56. }
  57. static void swReactor_onFinish(swReactor *reactor)
  58. {
  59. //check signal
  60. if (reactor->singal_no)
  61. {
  62. swSignal_callback(reactor->singal_no);
  63. reactor->singal_no = 0;
  64. }
  65. swReactor_onTimeout_and_Finish(reactor);
  66. }
  67. static void swReactor_onTimeout_and_Finish(swReactor *reactor)
  68. {
  69. if (reactor->check_timer)
  70. {
  71. swTimer_select(&SwooleG.timer);
  72. }
  73. ...
  74. }
swSystemTimer_init 初始化

对于 worker 进程来说,由于定时任务比较多而且复杂,就不能简单使用 reactor 超时来实现功能。

swSystemTimer_init 采用 SIGALRM 闹钟信号或者 timefd 来触发中断 reactor 的等待。

对于 timefd 来说,需要使用 timerfd_settime 系统调用来设置超时时间,然后将 timefd 加入 workerreactor 监控中,将其当做文件描述符来监控。当其就绪时,会调用 swTimer_select 执行定时函数。

对于普通 SIGALRM 信号来说,将 timer->pipe 放入 reactor 的监控中,使用 setitimer 来定时触发 SIGALRM 信号,设置信号处理函数。信号处理函数中,会向 timer->pipe 写入数据,进而触发 swTimer_select 执行定时函数。

</>复制代码

  1. int swSystemTimer_init(int interval, int use_pipe)
  2. {
  3. swTimer *timer = &SwooleG.timer;
  4. timer->lasttime = interval;
  5. #ifndef HAVE_TIMERFD
  6. SwooleG.use_timerfd = 0;
  7. #endif
  8. if (SwooleG.use_timerfd)
  9. {
  10. if (swSystemTimer_timerfd_set(timer, interval) < 0)
  11. {
  12. return SW_ERR;
  13. }
  14. timer->use_pipe = 0;
  15. }
  16. else
  17. {
  18. if (use_pipe)
  19. {
  20. if (swPipeNotify_auto(&timer->pipe, 0, 0) < 0)
  21. {
  22. return SW_ERR;
  23. }
  24. timer->fd = timer->pipe.getFd(&timer->pipe, 0);
  25. timer->use_pipe = 1;
  26. }
  27. else
  28. {
  29. timer->fd = 1;
  30. timer->use_pipe = 0;
  31. }
  32. if (swSystemTimer_signal_set(timer, interval) < 0)
  33. {
  34. return SW_ERR;
  35. }
  36. swSignal_add(SIGALRM, swSystemTimer_signal_handler);
  37. }
  38. if (timer->fd > 1)
  39. {
  40. SwooleG.main_reactor->setHandle(SwooleG.main_reactor, SW_FD_TIMER, swSystemTimer_event_handler);
  41. SwooleG.main_reactor->add(SwooleG.main_reactor, SwooleG.timer.fd, SW_FD_TIMER);
  42. }
  43. timer->set = swSystemTimer_set;
  44. return SW_OK;
  45. }
swSystemTimer_timerfd_set 设置 timefd

该函数目的是使用 timerfd_settime 系统调用,该系统调用需要 timefditimerspec 类型对象

timefd 可以由 timerfd_create 系统函数创建

itimerspec 对象需要当前时间和 interval 间隔时间共同设置。it_value 是首次超时时间,需要填写当前时间,并加上要超时的时间,值得注意的是 tv_nsec 加上去后一定要判断是否超出1000000000(如果超过要秒加一),否则会设置失败;it_interval 是后续周期性超时时间。

</>复制代码

  1. static int swSystemTimer_timerfd_set(swTimer *timer, long interval)
  2. {
  3. struct timeval now;
  4. int sec = interval / 1000;
  5. int msec = (((float) interval / 1000) - sec) * 1000;
  6. if (gettimeofday(&now, NULL) < 0)
  7. {
  8. swWarn("gettimeofday() failed. Error: %s[%d]", strerror(errno), errno);
  9. return SW_ERR;
  10. }
  11. struct itimerspec timer_set;
  12. bzero(&timer_set, sizeof(timer_set));
  13. if (interval < 0)
  14. {
  15. if (timer->fd == 0)
  16. {
  17. return SW_OK;
  18. }
  19. }
  20. else
  21. {
  22. timer_set.it_interval.tv_sec = sec;
  23. timer_set.it_interval.tv_nsec = msec * 1000 * 1000;
  24. timer_set.it_value.tv_sec = now.tv_sec + sec;
  25. timer_set.it_value.tv_nsec = (now.tv_usec * 1000) + timer_set.it_interval.tv_nsec;
  26. if (timer_set.it_value.tv_nsec > 1e9)
  27. {
  28. timer_set.it_value.tv_nsec = timer_set.it_value.tv_nsec - 1e9;
  29. timer_set.it_value.tv_sec += 1;
  30. }
  31. if (timer->fd == 0)
  32. {
  33. timer->fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK | TFD_CLOEXEC);
  34. if (timer->fd < 0)
  35. {
  36. swWarn("timerfd_create() failed. Error: %s[%d]", strerror(errno), errno);
  37. return SW_ERR;
  38. }
  39. }
  40. }
  41. if (timerfd_settime(timer->fd, TFD_TIMER_ABSTIME, &timer_set, NULL) == -1)
  42. {
  43. swWarn("timerfd_settime() failed. Error: %s[%d]", strerror(errno), errno);
  44. return SW_ERR;
  45. }
  46. return SW_OK;
  47. #else
  48. swWarn("kernel not support timerfd.");
  49. return SW_ERR;
  50. #endif
  51. }
swSystemTimer_signal_set 设置信号超时时间

setitimer 是一个比较常用的函数,可用来实现延时和定时的功能。

ITIMER_REAL:以系统真实的时间来计算,它送出 SIGALRM 信号。

ITIMER_VIRTUAL:以该进程在用户态下花费的时间来计算,它送出 SIGVTALRM 信号。

ITIMER_PROF:以该进程在用户态下和内核态下所费的时间来计算,它送出 SIGPROF 信号。

it_interval 为计时间隔,it_value 为延时时长,也就是距离现有时间第一次延迟触发的相对时间,而不是绝对时间。(所以我认为代码中 gettimeofday 函数是多余的,并不需要获取当前时间)

</>复制代码

  1. */
  2. static int swSystemTimer_signal_set(swTimer *timer, long interval)
  3. {
  4. struct itimerval timer_set;
  5. int sec = interval / 1000;
  6. int msec = (((float) interval / 1000) - sec) * 1000;
  7. struct timeval now;
  8. if (gettimeofday(&now, NULL) < 0)
  9. {
  10. swWarn("gettimeofday() failed. Error: %s[%d]", strerror(errno), errno);
  11. return SW_ERR;
  12. }
  13. bzero(&timer_set, sizeof(timer_set));
  14. if (interval > 0)
  15. {
  16. timer_set.it_interval.tv_sec = sec;
  17. timer_set.it_interval.tv_usec = msec * 1000;
  18. timer_set.it_value.tv_sec = sec;
  19. timer_set.it_value.tv_usec = timer_set.it_interval.tv_usec;
  20. if (timer_set.it_value.tv_usec > 1e6)
  21. {
  22. timer_set.it_value.tv_usec = timer_set.it_value.tv_usec - 1e6;
  23. timer_set.it_value.tv_sec += 1;
  24. }
  25. }
  26. if (setitimer(ITIMER_REAL, &timer_set, NULL) < 0)
  27. {
  28. swWarn("setitimer() failed. Error: %s[%d]", strerror(errno), errno);
  29. return SW_ERR;
  30. }
  31. return SW_OK;
  32. }
swSystemTimer_signal_handler 超时信号处理函数

swSystemTimer_signal_handler 函数是 SIGALARM 信号的处理函数,该函数被触发说明 epoll_wait 函数被闹钟信号中断,此时本函数向 timer.pipe 写入数据,然后即返回。reactor 会检测到 timer.pipe 的写就绪,进而调用对应的回调函数 swSystemTimer_event_handler

</>复制代码

  1. void swSystemTimer_signal_handler(int sig)
  2. {
  3. SwooleG.signal_alarm = 1;
  4. uint64_t flag = 1;
  5. if (SwooleG.timer.use_pipe)
  6. {
  7. SwooleG.timer.pipe.write(&SwooleG.timer.pipe, &flag, sizeof(flag));
  8. }
  9. }
swSystemTimer_event_handler 写就绪回调函数

写就绪回调函数可能是由 timer.pipe 的写就绪触发,也可能是 timefd 的写就绪触发,无论哪个都会调用 swTimer_select 函数执行对应的定时函数。

</>复制代码

  1. int swSystemTimer_event_handler(swReactor *reactor, swEvent *event)
  2. {
  3. uint64_t exp;
  4. swTimer *timer = &SwooleG.timer;
  5. if (read(timer->fd, &exp, sizeof(uint64_t)) != sizeof(uint64_t))
  6. {
  7. return SW_ERR;
  8. }
  9. SwooleG.signal_alarm = 0;
  10. return swTimer_select(timer);
  11. }
swTimer_add 添加元素

swTimer_add 用于添加定时函数元素。本函数逻辑比较简单,新建一个 swTimer_node 对象,初始化赋值之后加入到 timer->heap 中,程序会自动根据其 exec_msec 进行有小到大的排序,然后再更新 timer->map 哈希表。

值得注意的是,当新添加的定时函数需要执行的时间小于当前 timer 下次执行时间的时候,我们需要调用 timer->set 函数更新 time 的间隔时间。在 master 进程中,这个 set 函数是 swReactorTimer_set,用于设置 reactor 的超时时间;在 worker 进程中,set 函数是 swSystemTimer_set,用于更新 timerfd_settimesetitimer 函数。

</>复制代码

  1. static swTimer_node* swTimer_add(swTimer *timer, int _msec, int interval, void *data, swTimerCallback callback)
  2. {
  3. swTimer_node *tnode = sw_malloc(sizeof(swTimer_node));
  4. if (!tnode)
  5. {
  6. swSysError("malloc(%ld) failed.", sizeof(swTimer_node));
  7. return NULL;
  8. }
  9. int64_t now_msec = swTimer_get_relative_msec();
  10. if (now_msec < 0)
  11. {
  12. sw_free(tnode);
  13. return NULL;
  14. }
  15. tnode->data = data;
  16. tnode->type = SW_TIMER_TYPE_KERNEL;
  17. tnode->exec_msec = now_msec + _msec;
  18. tnode->interval = interval ? _msec : 0;
  19. tnode->remove = 0;
  20. tnode->callback = callback;
  21. if (timer->_next_msec < 0 || timer->_next_msec > _msec)
  22. {
  23. timer->set(timer, _msec);
  24. timer->_next_msec = _msec;
  25. }
  26. tnode->id = timer->_next_id++;
  27. if (unlikely(tnode->id < 0))
  28. {
  29. tnode->id = 1;
  30. timer->_next_id = 2;
  31. }
  32. timer->num++;
  33. tnode->heap_node = swHeap_push(timer->heap, tnode->exec_msec, tnode);
  34. if (tnode->heap_node == NULL)
  35. {
  36. sw_free(tnode);
  37. return NULL;
  38. }
  39. swHashMap_add_int(timer->map, tnode->id, tnode);
  40. return tnode;
  41. }
  42. static int swSystemTimer_set(swTimer *timer, long new_interval)
  43. {
  44. if (new_interval == current_interval)
  45. {
  46. return SW_OK;
  47. }
  48. current_interval = new_interval;
  49. if (SwooleG.use_timerfd)
  50. {
  51. return swSystemTimer_timerfd_set(timer, new_interval);
  52. }
  53. else
  54. {
  55. return swSystemTimer_signal_set(timer, new_interval);
  56. }
  57. }
swTimer_del 删除元素

</>复制代码

  1. int swTimer_del(swTimer *timer, swTimer_node *tnode)
  2. {
  3. if (tnode->remove)
  4. {
  5. return SW_FALSE;
  6. }
  7. if (SwooleG.timer._current_id > 0 && tnode->id == SwooleG.timer._current_id)
  8. {
  9. tnode->remove = 1;
  10. return SW_TRUE;
  11. }
  12. if (swHashMap_del_int(timer->map, tnode->id) < 0)
  13. {
  14. return SW_ERR;
  15. }
  16. if (tnode->heap_node)
  17. {
  18. //remove from min-heap
  19. swHeap_remove(timer->heap, tnode->heap_node);
  20. sw_free(tnode->heap_node);
  21. }
  22. sw_free(tnode);
  23. timer->num --;
  24. return SW_TRUE;
  25. }
swTimer_select 筛选定时函数

swTimer_select 函数的筛选原理是从 timer->heap 中不断 pop 出定时元素,比较它们的 exec_msec 是否超过了当前时间,如果超过了时间,就执行对应的定时函数;如果没有超过,由于 timer->heap 是排序过后的数据堆,因此当前定时元素之后的都不会超过当前时间,也就是还没有到执行的时间。

如果当前的定时元素超过了当前时间,说明该元素应该执行定时函数。设置 timer->_current_id 为当前的 id 后,执行 tnode->callback 回调函数;如果当前定时元素不是一次执行的任务,而是需要每隔一段时间定时的任务,就要再次将元素放入 timer->heap 中;如果当前定时元素是一次执行的任务,就要将元素从 timer->maptimer->map 中删除

循环结束后,tnode 就是下一个要执行的定时元素,我们需要调用 timer->set 函数设置闹钟信号(worker 进程)或者 reactor 超时时间(master 进程)。

</>复制代码

  1. int swTimer_select(swTimer *timer)
  2. {
  3. int64_t now_msec = swTimer_get_relative_msec();
  4. if (now_msec < 0)
  5. {
  6. return SW_ERR;
  7. }
  8. swTimer_node *tnode = NULL;
  9. swHeap_node *tmp;
  10. long timer_id;
  11. while ((tmp = swHeap_top(timer->heap)))
  12. {
  13. tnode = tmp->data;
  14. if (tnode->exec_msec > now_msec)
  15. {
  16. break;
  17. }
  18. timer_id = timer->_current_id = tnode->id;
  19. if (!tnode->remove)
  20. {
  21. tnode->callback(timer, tnode);
  22. }
  23. timer->_current_id = -1;
  24. //persistent timer
  25. if (tnode->interval > 0 && !tnode->remove)
  26. {
  27. while (tnode->exec_msec <= now_msec)
  28. {
  29. tnode->exec_msec += tnode->interval;
  30. }
  31. swHeap_change_priority(timer->heap, tnode->exec_msec, tmp);
  32. continue;
  33. }
  34. timer->num--;
  35. swHeap_pop(timer->heap);
  36. swHashMap_del_int(timer->map, timer_id);
  37. sw_free(tnode);
  38. }
  39. if (!tnode || !tmp)
  40. {
  41. timer->_next_msec = -1;
  42. timer->set(timer, -1);
  43. }
  44. else
  45. {
  46. timer->set(timer, tnode->exec_msec - now_msec);
  47. }
  48. return SW_OK;
  49. }
Timer 定时器的使用 master 进程 swServer_start_proxy

timer 模块在 master 进程中最重要的作用是每隔一秒更新 serv->gs->now 的值。除此之外,当 reactor 线程调度 worker 进程时,如果一段时间内没有任何空闲的 worker 进程空闲,timer 模块还负责写入错误日志。

</>复制代码

  1. static int swServer_start_proxy(swServer *serv)
  2. {
  3. ...
  4. if (swTimer_init(1000) < 0)
  5. {
  6. return SW_ERR;
  7. }
  8. if (SwooleG.timer.add(&SwooleG.timer, 1000, 1, serv, swServer_master_onTimer) == NULL)
  9. {
  10. return SW_ERR;
  11. }
  12. ...
  13. }
  14. void swServer_master_onTimer(swTimer *timer, swTimer_node *tnode)
  15. {
  16. swServer *serv = (swServer *) tnode->data;
  17. swServer_update_time(serv);
  18. if (serv->scheduler_warning && serv->warning_time < serv->gs->now)
  19. {
  20. serv->scheduler_warning = 0;
  21. serv->warning_time = serv->gs->now;
  22. swoole_error_log(SW_LOG_WARNING, SW_ERROR_SERVER_NO_IDLE_WORKER, "No idle worker is available.");
  23. }
  24. if (serv->hooks[SW_SERVER_HOOK_MASTER_TIMER])
  25. {
  26. swServer_call_hook(serv, SW_SERVER_HOOK_MASTER_TIMER, serv);
  27. }
  28. }
  29. void swServer_update_time(swServer *serv)
  30. {
  31. time_t now = time(NULL);
  32. if (now < 0)
  33. {
  34. swWarn("get time failed. Error: %s[%d]", strerror(errno), errno);
  35. }
  36. else
  37. {
  38. serv->gs->now = now;
  39. }
  40. }
worker 进程超时停止

worker 进程将要停止时,并不会立刻停止,而是会等待事件循环结束后停止,这时为了防止 worker 进程不退出,还设置了 30s 的延迟,超过 30s 就会停止该进程。

</>复制代码

  1. static void swWorker_stop()
  2. {
  3. swWorker *worker = SwooleWG.worker;
  4. swServer *serv = SwooleG.serv;
  5. worker->status = SW_WORKER_BUSY;
  6. ...
  7. try_to_exit: SwooleWG.wait_exit = 1;
  8. if (SwooleG.timer.fd == 0)
  9. {
  10. swTimer_init(serv->max_wait_time * 1000);
  11. }
  12. SwooleG.timer.add(&SwooleG.timer, serv->max_wait_time * 1000, 0, NULL, swWorker_onTimeout);
  13. swWorker_try_to_exit();
  14. }
  15. static void swWorker_onTimeout(swTimer *timer, swTimer_node *tnode)
  16. {
  17. SwooleG.running = 0;
  18. SwooleG.main_reactor->running = 0;
  19. swoole_error_log(SW_LOG_WARNING, SW_ERROR_SERVER_WORKER_EXIT_TIMEOUT, "worker exit timeout, forced to terminate.");
  20. }
swoole_timer_tick 添加定时任务

timer 模块另一个非常重要的功能是添加定时任务,一般是使用 swoole_timer_tick 函数、swoole_timer_after 函数、swoole_server->tick 函数、swoole_server->after 函数:

</>复制代码

  1. PHP_FUNCTION(swoole_timer_tick)
  2. {
  3. long after_ms;
  4. zval *callback;
  5. zval *param = NULL;
  6. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lz|z", &after_ms, &callback, ¶m) == FAILURE)
  7. {
  8. return;
  9. }
  10. long timer_id = php_swoole_add_timer(after_ms, callback, param, 1 TSRMLS_CC);
  11. if (timer_id < 0)
  12. {
  13. RETURN_FALSE;
  14. }
  15. else
  16. {
  17. RETURN_LONG(timer_id);
  18. }
  19. }
  20. PHP_FUNCTION(swoole_timer_after)
  21. {
  22. long after_ms;
  23. zval *callback;
  24. zval *param = NULL;
  25. if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "lz|z", &after_ms, &callback, ¶m) == FAILURE)
  26. {
  27. return;
  28. }
  29. long timer_id = php_swoole_add_timer(after_ms, callback, param, 0 TSRMLS_CC);
  30. if (timer_id < 0)
  31. {
  32. RETURN_FALSE;
  33. }
  34. else
  35. {
  36. RETURN_LONG(timer_id);
  37. }
  38. }
php_swoole_add_timer 函数

本函数主要调用 SwooleG.timer.add 函数将添加新的定时任务,值得注意的是 swTimer_callback 类型的对象 cb 和两个回调函数 php_swoole_onIntervalphp_swoole_onTimeout,真正的回调函数存放在了 swTimer_callback 对象中,如果用户有参数设置,也会放入 cb->data 中。

</>复制代码

  1. long php_swoole_add_timer(int ms, zval *callback, zval *param, int persistent TSRMLS_DC)
  2. {
  3. char *func_name = NULL;
  4. if (!swIsTaskWorker())
  5. {
  6. php_swoole_check_reactor();
  7. }
  8. php_swoole_check_timer(ms);
  9. swTimer_callback *cb = emalloc(sizeof(swTimer_callback));
  10. cb->data = &cb->_data;
  11. cb->callback = &cb->_callback;
  12. memcpy(cb->callback, callback, sizeof(zval));
  13. if (param)
  14. {
  15. memcpy(cb->data, param, sizeof(zval));
  16. }
  17. else
  18. {
  19. cb->data = NULL;
  20. }
  21. swTimerCallback timer_func;
  22. if (persistent)
  23. {
  24. cb->type = SW_TIMER_TICK;
  25. timer_func = php_swoole_onInterval;
  26. }
  27. else
  28. {
  29. cb->type = SW_TIMER_AFTER;
  30. timer_func = php_swoole_onTimeout;
  31. }
  32. sw_zval_add_ref(&cb->callback);
  33. if (cb->data)
  34. {
  35. sw_zval_add_ref(&cb->data);
  36. }
  37. swTimer_node *tnode = SwooleG.timer.add(&SwooleG.timer, ms, persistent, cb, timer_func);
  38. {
  39. tnode->type = SW_TIMER_TYPE_PHP;
  40. return tnode->id;
  41. }
  42. }
  43. void php_swoole_check_timer(int msec)
  44. {
  45. if (unlikely(SwooleG.timer.fd == 0))
  46. {
  47. swTimer_init(msec);
  48. }
  49. }
php_swoole_onInterval 函数

本函数主要调用 cb->callback,如果有用户参数,还要将 cb->data 放入调用函数中。

</>复制代码

  1. void php_swoole_onInterval(swTimer *timer, swTimer_node *tnode)
  2. {
  3. zval *retval = NULL;
  4. int argc = 1;
  5. zval *ztimer_id;
  6. swTimer_callback *cb = tnode->data;
  7. SW_MAKE_STD_ZVAL(ztimer_id);
  8. ZVAL_LONG(ztimer_id, tnode->id);
  9. {
  10. zval **args[2];
  11. if (cb->data)
  12. {
  13. argc = 2;
  14. sw_zval_add_ref(&cb->data);
  15. args[1] = &cb->data;
  16. }
  17. args[0] = &ztimer_id;
  18. if (sw_call_user_function_ex(EG(function_table), NULL, cb->callback, &retval, argc, args, 0, NULL TSRMLS_CC) == FAILURE)
  19. {
  20. swoole_php_fatal_error(E_WARNING, "swoole_timer: onTimerCallback handler error");
  21. return;
  22. }
  23. }
  24. if (tnode->remove)
  25. {
  26. php_swoole_del_timer(tnode TSRMLS_CC);
  27. }
  28. }
php_swoole_onTimeout 函数

与上一个函数类似,只是这次直接从 timer 中删除对应的元素。

</>复制代码

  1. void php_swoole_onTimeout(swTimer *timer, swTimer_node *tnode)
  2. {
  3. {
  4. swTimer_callback *cb = tnode->data;
  5. zval *retval = NULL;
  6. {
  7. zval **args[2];
  8. int argc;
  9. if (NULL == cb->data)
  10. {
  11. argc = 0;
  12. args[0] = NULL;
  13. }
  14. else
  15. {
  16. argc = 1;
  17. args[0] = &cb->data;
  18. }
  19. if (sw_call_user_function_ex(EG(function_table), NULL, cb->callback, &retval, argc, args, 0, NULL TSRMLS_CC) == FAILURE)
  20. {
  21. swoole_php_fatal_error(E_WARNING, "swoole_timer: onTimeout handler error");
  22. return;
  23. }
  24. }
  25. php_swoole_del_timer(tnode TSRMLS_CC);
  26. }
  27. }
Timer 模块时间轮算法

时间轮算法是各大网络模块采用的剔除空闲连接的方法,原理是构建一个首尾相连的循环数组,每隔数组元素中有若干个连接。如果某个连接有数据发送过来,将连接从所在的数组元素中删除,将连接放入最新的数组元素中,这样有数据来往的连接会一直在新数组元素中,空闲的连接所在的数组元素渐渐的变成了旧数组元素。每隔一段时间就按顺序清空旧数组元素的全部连接。

swTimeWheel_new 创建时间轮

时间轮的数据结构比较简单,由哈希表、size(循环数组总数量),current (循环数组当前最旧的数组元素,current-1 是循环数组中最新的数组元素)。swTimeWheel_new 函数很简单,就是创建这三个属性。

</>复制代码

  1. typedef struct
  2. {
  3. uint16_t current;
  4. uint16_t size;
  5. swHashMap **wheel;
  6. } swTimeWheel;
  7. swTimeWheel* swTimeWheel_new(uint16_t size)
  8. {
  9. swTimeWheel *tw = sw_malloc(sizeof(swTimeWheel));
  10. if (!tw)
  11. {
  12. swWarn("malloc(%ld) failed.", sizeof(swTimeWheel));
  13. return NULL;
  14. }
  15. tw->size = size;
  16. tw->current = 0;
  17. tw->wheel = sw_calloc(size, sizeof(void*));
  18. if (tw->wheel == NULL)
  19. {
  20. swWarn("malloc(%ld) failed.", sizeof(void*) * size);
  21. sw_free(tw);
  22. return NULL;
  23. }
  24. int i;
  25. for (i = 0; i < size; i++)
  26. {
  27. tw->wheel[i] = swHashMap_new(16, NULL);
  28. if (tw->wheel[i] == NULL)
  29. {
  30. swTimeWheel_free(tw);
  31. return NULL;
  32. }
  33. }
  34. return tw;
  35. }
swTimeWheel_add 添加连接

main_reactor 有新连接进入的时候,需要将新的连接添加到时间轮中,新的连接会被放到最新的数组元素中,也就是 current-1 的元素中,然后设置 swConnection 中的 timewheel_index

</>复制代码

  1. void swTimeWheel_add(swTimeWheel *tw, swConnection *conn)
  2. {
  3. uint16_t index = tw->current == 0 ? tw->size - 1 : tw->current - 1;
  4. swHashMap *new_set = tw->wheel[index];
  5. swHashMap_add_int(new_set, conn->fd, conn);
  6. conn->timewheel_index = index;
  7. swTraceLog(SW_TRACE_REACTOR, "current=%d, fd=%d, index=%d.", tw->current, conn->fd, index);
  8. }
swTimeWheel_update 函数

当连接有数据传输的时候,需要更新该连接在时间轮中的位置,将该连接从原有的数组元素中删除,然后添加到最新的数组元素中,也就是 current-1 中,然后更新 swConnection 中的 timewheel_index

</>复制代码

  1. #define swTimeWheel_new_index(tw) (tw->current == 0 ? tw->size - 1 : tw->current - 1)
  2. void swTimeWheel_update(swTimeWheel *tw, swConnection *conn)
  3. {
  4. uint16_t new_index = swTimeWheel_new_index(tw);
  5. swHashMap *new_set = tw->wheel[new_index];
  6. swHashMap_add_int(new_set, conn->fd, conn);
  7. swHashMap *old_set = tw->wheel[conn->timewheel_index];
  8. swHashMap_del_int(old_set, conn->fd);
  9. swTraceLog(SW_TRACE_REACTOR, "current=%d, fd=%d, old_index=%d, new_index=%d.", tw->current, conn->fd, new_index, conn->timewheel_index);
  10. conn->timewheel_index = new_index;
  11. }
swTimeWheel_remove 函数

在时间轮中删除该连接,

</>复制代码

  1. void swTimeWheel_remove(swTimeWheel *tw, swConnection *conn)
  2. {
  3. swHashMap *set = tw->wheel[conn->timewheel_index];
  4. swHashMap_del_int(set, conn->fd);
  5. swTraceLog(SW_TRACE_REACTOR, "current=%d, fd=%d.", tw->current, conn->fd);
  6. }
swTimeWheel_forward 删除空闲连接

swTimeWheel_forward 将最旧的数组元素 current 中所有连接都关闭掉,然后将 current 递增。

</>复制代码

  1. void swTimeWheel_forward(swTimeWheel *tw, swReactor *reactor)
  2. {
  3. swHashMap *set = tw->wheel[tw->current];
  4. tw->current = tw->current == tw->size - 1 ? 0 : tw->current + 1;
  5. swTraceLog(SW_TRACE_REACTOR, "current=%d.", tw->current);
  6. swConnection *conn;
  7. uint64_t fd;
  8. while (1)
  9. {
  10. conn = swHashMap_each_int(set, &fd);
  11. if (conn == NULL)
  12. {
  13. break;
  14. }
  15. conn->close_force = 1;
  16. conn->close_notify = 1;
  17. conn->close_wait = 1;
  18. conn->close_actively = 1;
  19. //notify to reactor thread
  20. if (conn->removed)
  21. {
  22. reactor->close(reactor, (int) fd);
  23. }
  24. else
  25. {
  26. reactor->set(reactor, fd, SW_FD_TCP | SW_EVENT_WRITE);
  27. }
  28. }
  29. }
reactor 线程中时间轮的创建

时间轮的创建在 reactor 线程进行事件循环之前,按照用户设置的连接最大空闲时间设置不同大小的时间轮,值得注意的是,时间轮最大是 SW_TIMEWHEEL_SIZE,也就是循环数组大小最大是 60。如果超过 60s 空闲时间,也仅仅建立 60 个元素的数组,但是这样会造成每个数组元素存放更多的连接。

值得注意的是,当允许空闲时间超过 60s 时,heartbeat_interval * 1000reactor 的超时时间,例如空闲时间是 60s,那么每隔 6s,reactor 都会超时来检测空闲连接。当允许空闲时间小于 60s 时,reactor 统一每隔 1s 检测空闲连接。

不同于 master 进程和 worker 线程,reactoronFinishonTimeout 不再采用默认的 swReactor_onTimeoutswReactor_onFinish 函数,而是采用空闲连接检测的 swReactorThread_onReactorCompleted 函数,该函数会调用 swTimeWheel_forward 来剔除空闲连接。

</>复制代码

  1. #define SW_TIMEWHEEL_SIZE 60
  2. static int swReactorThread_loop(swThreadParam *param)
  3. {
  4. ...
  5. if (serv->heartbeat_idle_time > 0)
  6. {
  7. if (serv->heartbeat_idle_time < SW_TIMEWHEEL_SIZE)
  8. {
  9. reactor->timewheel = swTimeWheel_new(serv->heartbeat_idle_time);
  10. reactor->heartbeat_interval = 1;
  11. }
  12. else
  13. {
  14. reactor->timewheel = swTimeWheel_new(SW_TIMEWHEEL_SIZE);
  15. reactor->heartbeat_interval = serv->heartbeat_idle_time / SW_TIMEWHEEL_SIZE;
  16. }
  17. reactor->last_heartbeat_time = 0;
  18. if (reactor->timewheel == NULL)
  19. {
  20. swSysError("thread->timewheel create failed.");
  21. return SW_ERR;
  22. }
  23. reactor->timeout_msec = reactor->heartbeat_interval * 1000;
  24. reactor->onFinish = swReactorThread_onReactorCompleted;
  25. reactor->onTimeout = swReactorThread_onReactorCompleted;
  26. }
  27. reactor->wait(reactor, NULL);
  28. }
reactor 线程中时间轮的添加

当有新连接的时候,conn->connect_notify 会被置为 1,此时该连接文件描述符写就绪,然后就会调用 swReactorThread_onWrite,此时 reactor 线程将该连接添加到时间轮中。

</>复制代码

  1. static int swReactorThread_onWrite(swReactor *reactor, swEvent *ev)
  2. {
  3. ...
  4. if (conn->connect_notify)
  5. {
  6. conn->connect_notify = 0;
  7. if (reactor->timewheel)
  8. {
  9. swTimeWheel_add(reactor->timewheel, conn);
  10. }
  11. ...
  12. }
  13. ...
  14. }
reactor 线程中时间轮的更新

</>复制代码

  1. static int swReactorThread_onRead(swReactor *reactor, swEvent *event)
  2. {
  3. ...
  4. if (reactor->timewheel && swTimeWheel_new_index(reactor->timewheel) != event->socket->timewheel_index)
  5. {
  6. swTimeWheel_update(reactor->timewheel, event->socket);
  7. }
  8. ...
  9. }
reactor 线程中时间轮的剔除

当连接在允许的空闲时间之内没有任何数据发送,那么时间轮算法就要关闭该连接。关闭连接并不是直接 close 套接字,而是需要通知对应的 worker 进程调用 onClose 函数,然后才能关闭。具体的做法是设置 swConnectionclose_forceclose_notify 等成员变量为 1,并且关闭该连接的读就绪监听事件。

</>复制代码

  1. static void swReactorThread_onReactorCompleted(swReactor *reactor)
  2. {
  3. swServer *serv = reactor->ptr;
  4. if (reactor->heartbeat_interval > 0 && reactor->last_heartbeat_time < serv->gs->now - reactor->heartbeat_interval)
  5. {
  6. swTimeWheel_forward(reactor->timewheel, reactor);
  7. reactor->last_heartbeat_time = serv->gs->now;
  8. }
  9. }
  10. void swTimeWheel_forward(swTimeWheel *tw, swReactor *reactor)
  11. {
  12. ...
  13. conn->close_force = 1;
  14. conn->close_notify = 1;
  15. conn->close_wait = 1;
  16. conn->close_actively = 1;
  17. if (conn->removed)
  18. {
  19. reactor->close(reactor, (int) fd);
  20. }
  21. else
  22. {
  23. reactor->set(reactor, fd, SW_FD_TCP | SW_EVENT_WRITE);
  24. }
  25. ...
  26. }

当该连接写就绪的时候,会调用 swReactorThread_onWrite 函数。这个时候就会调用 swServer_tcp_notify 函数,进而调用 swFactoryProcess_notifyswFactoryProcess_dispatch,最后调用 swReactorThread_send2worker 发送给了 worker 进程。

由于 reactor 启用的是水平触发,由于并未向该连接写入数据,因此很快又会触发写就绪事件调用 swReactorThread_onWrite 函数,这时如果 disable_notify 为 1(dispatch_mode 为 1 或 3),会直接执行 swReactorThread_close 函数关闭连接,假如此时 conn->out_buffer 中还有数据未发送,也会被抛弃。如果 disable_notify 为 0,则会继续向将要关闭的连接发送数据,直到接收到 SW_CHUNK_CLOSE 类型的消息。

</>复制代码

  1. static int swReactorThread_onWrite(swReactor *reactor, swEvent *ev)
  2. {
  3. ...
  4. else if (conn->close_notify)
  5. {
  6. swServer_tcp_notify(serv, conn, SW_EVENT_CLOSE);
  7. conn->close_notify = 0;
  8. return SW_OK;
  9. }
  10. else if (serv->disable_notify && conn->close_force)
  11. {
  12. return swReactorThread_close(reactor, fd);
  13. }
  14. ...
  15. }
  16. int swServer_tcp_notify(swServer *serv, swConnection *conn, int event)
  17. {
  18. swDataHead notify_event;
  19. notify_event.type = event;
  20. notify_event.from_id = conn->from_id;
  21. notify_event.fd = conn->fd;
  22. notify_event.from_fd = conn->from_fd;
  23. notify_event.len = 0;
  24. return serv->factory.notify(&serv->factory, ¬ify_event);
  25. }
  26. static int swFactoryProcess_notify(swFactory *factory, swDataHead *ev)
  27. {
  28. memcpy(&sw_notify_data._send, ev, sizeof(swDataHead));
  29. sw_notify_data._send.len = 0;
  30. sw_notify_data.target_worker_id = -1;
  31. return factory->dispatch(factory, (swDispatchData *) &sw_notify_data);
  32. }
  33. static int swFactoryProcess_dispatch(swFactory *factory, swDispatchData *task)
  34. {
  35. ...
  36. if (swEventData_is_stream(task->data.info.type))
  37. {
  38. swConnection *conn = swServer_connection_get(serv, fd);
  39. if (conn->closed)
  40. {
  41. //Connection has been clsoed by server
  42. if (!(task->data.info.type == SW_EVENT_CLOSE && conn->close_force))
  43. {
  44. return SW_OK;
  45. }
  46. }
  47. //converted fd to session_id
  48. task->data.info.fd = conn->session_id;
  49. task->data.info.from_fd = conn->from_fd;
  50. }
  51. return swReactorThread_send2worker((void *) &(task->data), send_len, target_worker_id);
  52. }

worker 进程收到消息后会调用 swWorker_onTask 函数,进而调用 swFactoryProcess_end 函数,调用 serv->onClose 函数,并设置 swConnection 对象的 closed 为 1,然后调用 swFactoryProcess_finish 函数将数据包发送给 reactor 线程。

</>复制代码

  1. int swWorker_onTask(swFactory *factory, swEventData *task)
  2. {
  3. switch (task->info.type)
  4. {
  5. ...
  6. factory->end(factory, task->info.fd);
  7. break;
  8. ...
  9. }
  10. }
  11. static int swFactoryProcess_end(swFactory *factory, int fd)
  12. {
  13. bzero(&_send, sizeof(_send));
  14. _send.info.fd = fd;
  15. _send.info.len = 0;
  16. _send.info.type = SW_EVENT_CLOSE;
  17. swConnection *conn = swWorker_get_connection(serv, fd);
  18. if (conn->close_force)
  19. {
  20. goto do_close;
  21. }
  22. else if (conn->closing)
  23. {
  24. swoole_error_log(SW_LOG_NOTICE, SW_ERROR_SESSION_CLOSING, "The connection[%d] is closing.", fd);
  25. return SW_ERR;
  26. }
  27. else if (conn->closed)
  28. {
  29. return SW_ERR;
  30. }
  31. else
  32. {
  33. do_close:
  34. conn->closing = 1;
  35. if (serv->onClose != NULL)
  36. {
  37. info.fd = fd;
  38. if (conn->close_actively)
  39. {
  40. info.from_id = -1;
  41. }
  42. else
  43. {
  44. info.from_id = conn->from_id;
  45. }
  46. info.from_fd = conn->from_fd;
  47. serv->onClose(serv, &info);
  48. }
  49. conn->closing = 0;
  50. conn->closed = 1;
  51. conn->close_errno = 0;
  52. return factory->finish(factory, &_send);
  53. }
  54. }

reactor 通过 swReactorThread_onPipeReceive 收到 worker 进程的连接关闭通知后,调用 swReactorThread_send 函数。如果连接已经被关闭,或者缓冲区中没有任何数据的时候,直接调用 reactor->close 函数,也就是 swReactorThread_close 函数;如果缓冲区还有数据,那么需要将消息放到 conn->out_buffer 中等待着该连接写就绪回调 swReactorThread_close 函数(此时 close_notify 已经为 0)。

</>复制代码

  1. int swReactorThread_send(swSendData *_send)
  2. {
  3. ...
  4. if (_send->info.type == SW_EVENT_CLOSE && (conn->close_reset || conn->removed))
  5. {
  6. goto close_fd;
  7. }
  8. ...
  9. if (swBuffer_empty(conn->out_buffer))
  10. {
  11. if (_send->info.type == SW_EVENT_CLOSE)
  12. {
  13. close_fd:
  14. reactor->close(reactor, fd);
  15. return SW_OK;
  16. }
  17. }
  18. swBuffer_chunk *chunk;
  19. //close connection
  20. if (_send->info.type == SW_EVENT_CLOSE)
  21. {
  22. chunk = swBuffer_new_chunk(conn->out_buffer, SW_CHUNK_CLOSE, 0);
  23. chunk->store.data.val1 = _send->info.type;
  24. }
  25. if (reactor->set(reactor, fd, SW_EVENT_TCP | SW_EVENT_WRITE | SW_EVENT_READ) < 0
  26. && (errno == EBADF || errno == ENOENT))
  27. {
  28. goto close_fd;
  29. }
  30. ...
  31. close_fd:
  32. reactor->close(reactor, fd);
  33. return SW_OK;
  34. }
  35. static int swReactorThread_onWrite(swReactor *reactor, swEvent *ev)
  36. {
  37. ...
  38. else if (conn->close_notify)
  39. {
  40. swServer_tcp_notify(serv, conn, SW_EVENT_CLOSE);
  41. conn->close_notify = 0;
  42. return SW_OK;
  43. }
  44. else if (serv->disable_notify && conn->close_force)
  45. {
  46. return swReactorThread_close(reactor, fd);
  47. }
  48. _pop_chunk: while (!swBuffer_empty(conn->out_buffer))
  49. {
  50. chunk = swBuffer_get_chunk(conn->out_buffer);
  51. if (chunk->type == SW_CHUNK_CLOSE)
  52. {
  53. close_fd: reactor->close(reactor, fd);
  54. return SW_OK;
  55. }
  56. ...
  57. }
  58. ...
  59. }

swReactorThread_close 函数会删除 swConnectionserver 中的所有痕迹,包括 reactor 中的监控,serv->stats 的成员变量,port->connection_num 递减,从时间轮中删除、sessionfd 置空等等工作。而且,还要清空套接字缓存中的所有数据,直接向客户端发送关闭请求。swReactor_close 函数释放内存,关闭套接字文件描述符。

</>复制代码

  1. int swReactorThread_close(swReactor *reactor, int fd)
  2. {
  3. swServer *serv = SwooleG.serv;
  4. if (conn->removed == 0 && reactor->del(reactor, fd) < 0)
  5. {
  6. return SW_ERR;
  7. }
  8. sw_atomic_fetch_add(&serv->stats->close_count, 1);
  9. sw_atomic_fetch_sub(&serv->stats->connection_num, 1);
  10. swTrace("Close Event.fd=%d|from=%d", fd, reactor->id);
  11. //free the receive memory buffer
  12. swServer_free_buffer(serv, fd);
  13. swListenPort *port = swServer_get_port(serv, fd);
  14. sw_atomic_fetch_sub(&port->connection_num, 1);
  15. #ifdef SW_USE_SOCKET_LINGER
  16. if (conn->close_force)
  17. {
  18. struct linger linger;
  19. linger.l_onoff = 1;
  20. linger.l_linger = 0;
  21. if (setsockopt(fd, SOL_SOCKET, SO_LINGER, &linger, sizeof(struct linger)) == -1)
  22. {
  23. swWarn("setsockopt(SO_LINGER) failed. Error: %s[%d]", strerror(errno), errno);
  24. }
  25. }
  26. #endif
  27. #ifdef SW_REACTOR_USE_SESSION
  28. swSession *session = swServer_get_session(serv, conn->session_id);
  29. session->fd = 0;
  30. #endif
  31. #ifdef SW_USE_TIMEWHEEL
  32. if (reactor->timewheel)
  33. {
  34. swTimeWheel_remove(reactor->timewheel, conn);
  35. }
  36. #endif
  37. return swReactor_close(reactor, fd);
  38. }
  39. int swReactor_close(swReactor *reactor, int fd)
  40. {
  41. swConnection *socket = swReactor_get(reactor, fd);
  42. if (socket->out_buffer)
  43. {
  44. swBuffer_free(socket->out_buffer);
  45. }
  46. if (socket->in_buffer)
  47. {
  48. swBuffer_free(socket->in_buffer);
  49. }
  50. if (socket->websocket_buffer)
  51. {
  52. swString_free(socket->websocket_buffer);
  53. }
  54. bzero(socket, sizeof(swConnection));
  55. socket->removed = 1;
  56. swTraceLog(SW_TRACE_CLOSE, "fd=%d.", fd);
  57. return close(fd);
  58. }

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/29353.html

相关文章

  • Swoole 源码分析——Reactor模块ReactorBase

    前言 作为一个网络框架,最为核心的就是消息的接受与发送。高效的 reactor 模式一直是众多网络框架的首要选择,本节主要讲解 swoole 中的 reactor 模块。 UNP 学习笔记——IO 复用 Reactor 的数据结构 Reactor 的数据结构比较复杂,首先 object 是具体 Reactor 对象的首地址,ptr 是拥有 Reactor 对象的类的指针, event_nu...

    baukh789 评论0 收藏0
  • Swoole 源码分析——Server模块Start

    摘要:是缓存区高水位线,达到了说明缓冲区即将满了创建线程函数用于将监控的存放于中向中添加监听的文件描述符等待所有的线程开启事件循环利用创建线程,线程启动函数是保存监听本函数将用于监听的存放到当中,并设置相应的属性 Server 的启动 在 server 启动之前,swoole 首先要调用 php_swoole_register_callback 将 PHP 的回调函数注册到 server...

    3fuyu 评论0 收藏0
  • Swoole笔记(一)

    摘要:修复添加超过万个以上定时器时发生崩溃的问题增加模块,下高性能序列化库修复监听端口设置无效的问题等。线程来处理网络事件轮询,读取数据。当的三次握手成功了以后,由这个线程将连接成功的消息告诉进程,再由进程转交给进程。此时进程触发事件。 本文示例代码详见:https://github.com/52fhy/swoo...。 简介 Swoole是一个PHP扩展,提供了PHP语言的异步多线程服务器...

    SHERlocked93 评论0 收藏0
  • Swoole 源码分析——Client模块Send

    摘要:当此时的套接字不可写的时候,会自动放入缓冲区中。当大于高水线时,会自动调用回调函数。写就绪状态当监控到套接字进入了写就绪状态时,就会调用函数。如果为,说明此时异步客户端虽然建立了连接,但是还没有调用回调函数,因此这时要调用函数。 前言 上一章我们说了客户端的连接 connect,对于同步客户端来说,连接已经建立成功;但是对于异步客户端来说,此时可能还在进行 DNS 的解析,on...

    caozhijian 评论0 收藏0
  • Swoole 源码分析——Server模块Signal信号处理

    摘要:在创建进程和线程之间,主线程开始进行信号处理函数的设置。事件循环结束前会调用函数,该函数会检查并执行相应的信号处理函数。 前言 信号处理是网络库不可或缺的一部分,不论是 ALARM、SIGTERM、SIGUSR1、SIGUSR2、SIGPIPE 等信号对程序的控制,还是 reactor、read、write 等操作被信号中断的处理,都关系着整个框架程序的正常运行。 Signal 数据...

    Nosee 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<