【Tars】CoroutineScheduler中各函数的解释

本文详细介绍了Tars框架中的CoroutineScheduler,包括其核心数据结构如CoroutineInfo链表及不同状态的协程链表,以及相关函数的功能,如创建、调度、睡眠、唤醒和销毁协程等操作。

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

核心数据结构:
CoroutineInfo** _all_coro; // 存放所有协程的数组指针
CoroutineInfo _active; // 活跃的协程链表
CoroutineInfo _avail; // 可用的协程链表
CoroutineInfo _inactive; // 不活跃的协程链表
CoroutineInfo _timeout; // 超时的协程链表
CoroutineInfo _free; // 空闲的协程链表
list<uint32_t> _needActiveCoroId; // 需要激活的协程队列,本线程使用
multimap<int64_t, uint32_t> _timeoutCoroId; // 存放超时的协程


所有函数都是围绕上述核心数据结构进行的。各函数含义如下:

CoroutineInfo类:
CoroutineInfo节点是保存到一个双向链表里。一个CoroutineInfo代表一个协程。
CoroutineInfo::registerFunc函数:为协程设置一个callback函数。
CoroutineInfo::corotineEntry函数:对协程所属调度器设置一个什么东东。
CoroutineScheduler::increaseCoroPoolSize函数:同上,同理。
CoroutineInfo::corotineProc函数:调用指定协程的_callback函数,然后将此协程移到空闲链表中。scheduler切换到主协程。
CoroutineInfo::CoroutineDel函数:将指定协程从链表中单独拿出来。

CoroutineScheduler类:
CoroutineScheduler初始化:初始化一个_all_coro数组,所有协程都在里面。初始化一些空闲协程,放在_free链表中。设置当前协程为主协程。
CoroutineScheduler::increaseCoroPoolSize()函数:增加协程池大小,加入到_all_coro数组和_free链表中。
CoroutineScheduler::createCoroutine函数:从协程池_free中取出一个协程,放入_active中。
CoroutineScheduler::run()函数:逐个运行_active链表的协程。
CoroutineScheduler::tars_run()函数:逐个运行_active链表和_avail链表中的协程。
CoroutineScheduler::yield函数:让当前协程让CPU,将其放入_needActiveCoroId数组中,并且加入Inactive列表中。切换到主协程。
CoroutineScheduler::sleep函数:将当前协程加入到_timeoutCoroId数组中,并加入到_timeout链表中。
CoroutineScheduler::putbyself函数:将指定协程加入到_needActiveCoroId数组中
CoroutineScheduler::wakeupbyself()函数:将所有_needActiveCoroId中的协程都移到Avail链表队列中(即就绪队列中)。最后_needActiveCoroId变为空。
CoroutineScheduler::put函数:将指定协程加入到_activeCoroQueue数组中。
CoroutineScheduler::wakeup()函数:将_activeCoroQueue数组中的所有协程移动到active链表中。
CoroutineScheduler::wakeupbytimeout()函数:将所有_timeoutCoroId队列中的协程移动到Avail链表队列中。清空_timeoutCoroId。
CoroutineScheduler::terminate()函数:修改下_terminal变量即可。
CoroutineScheduler::generateId()函数:id一直不断地增加。
CoroutineScheduler::switchCoro函数:设置当前协程为指定协程。
CoroutineScheduler::moveToActive函数:将指定协程移动到Active链表中。
CoroutineScheduler::moveToInactive函数:将指定协程移动到_inactive链表中。
CoroutineScheduler::moveToTimeout函数:将指定协程移动到_timeout链表中。
CoroutineScheduler::moveToFreeList函数:将指定协程移动到空闲链表中。
CoroutineScheduler::destroy()函数:遍历_all_coro数组,释放所有协程资源。

Coroutine类:
Coroutine是对线程的包装,包含协程调度器。
Coroutine::terminate()函数:调度器终止。
Coroutine::handleCoro()函数:调用调度器的run()函数。
Coroutine::coroEntry函数:调用Coroutine的handle函数,handle在Coroutine中是个抽象函数。
Coroutine::createCoroutine函数:调用调度器的createCoroutine函数。
Coroutine::yield()函数:调用调度器的yield()函数。
Coroutine::Sleep函数:调度器sleep函数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值