协程的实现之调度器

一、协程如何被调度?

调度器的实现,有两种方案,一种是生产者消费者模式,另一种多状态运行。

1.1 生产者消费者模式

 

逻辑代码如下:

 1 while (1) {
 2 
 3         //遍历睡眠集合,将满足条件的加入到ready
 4         nty_coroutine *expired = NULL;
 5         while ((expired = sleep_tree_expired(sched)) != ) {
 6             TAILQ_ADD(&sched->ready, expired);
 7         }
 8 
 9         //遍历等待集合,将满足添加的加入到ready
10         nty_coroutine *wait = NULL;
11         int nready = epoll_wait(sched->epfd, events, EVENT_MAX, 1);
12         for (i = 0;i < nready;i ++) {
13             wait = wait_tree_search(events[i].data.fd);
14             TAILQ_ADD(&sched->ready, wait);
15         }
16 
17         // 使用resume回复ready的协程运行权
18         while (!TAILQ_EMPTY(&sched->ready)) {
19             nty_coroutine *ready = TAILQ_POP(sched->ready);
20             resume(ready);
21         }
22     }

1.2 多状态运行

 

实现逻辑代码如下:

 1 while (1) {
 2 
 3         //遍历睡眠集合,使用resume恢复expired的协程运行权
 4         nty_coroutine *expired = NULL;
 5         while ((expired = sleep_tree_expired(sched)) != ) {
 6             resume(expired);
 7         }
 8 
 9         //遍历等待集合,使用resume恢复wait的协程运行权
10         nty_coroutine *wait = NULL;
11         int nready = epoll_wait(sched->epfd, events, EVENT_MAX, 1);
12         for (i = 0;i < nready;i ++) {
13             wait = wait_tree_search(events[i].data.fd);
14             resume(wait);
15         }
16 
17         // 使用resume恢复ready的协程运行权
18         while (!TAILQ_EMPTY(sched->ready)) {
19             nty_coroutine *ready = TAILQ_POP(sched->ready);
20             resume(ready);
21         }
22     }

转载:

https://blog.csdn.net/Yttsam/article/details/107388747

posted @ 2021-07-24 16:04  Mr-xxx  阅读(184)  评论(0编辑  收藏  举报