1. 协程类封装
概念:协程是用户态的线程,仅仅完成代码序列的切换而不陷入内核态发生内核资源的切换。
基本原理:采用非对称协程开发。所有子协程的调度和创建依赖于一个母协程init_coroutine,即:一个线程需要启动协程时,首先会创建出一个默认的母协程。通过母协程让出当前代码序列在CPU的执行权,转让到子协程对应的代码序列中继续执行,子协程完毕后让出执行权又回到母协程中。

-
准备:依赖的库文件
**<ucontext.h>** 切换程序上下文API:
//依赖实现的结构体typedef struct ucontext {struct ucontext *uc_link; //后续的程序上下文sigset_t uc_sigmask; //当前上下文中的阻塞信号集合stack_t uc_stack; //当前上下文依赖的栈空间信息集合mcontext_t uc_mcontext;...} ucontext_t;
int getcontext(ucontext_t *ucp);保存当前程序上下文。int setcontext(const ucontext_t *ucp);将保存的程序上下文拿出推送到CPU上void makecontext(ucontext_t *ucp, void (*func)(), int argc, ...);创建新上下文int swapcontext(ucontext_t *oucp, ucontext_t *ucp);切换当前上下文 oucp——>ucp
**setcontext/swapcontext**会激活保存好的程序上下文去执行,也就意味着必须先调用**getcontext**
注意:使用makecontext时,必须先调用一次getcontext(个人猜测是因为,重新创建一个上下文使用除了要传函数的入口地址,其余的CPU寄存器值也要保存,getcontext可以代劳),然后为ucontext_t设置新的栈空间传入:uc_stack.ss_sp栈起始地址,uc_stack.ss_size栈空间大小、后续需要运行的上下文uc_link。
1.1 成员变量
/*** @brief 协程类*/class Coroutine: public std::enable_shared_from_this<Coroutine>{......public:/*** @brief 协程运行状态枚举类型*/enum State{INIT, //初始状态HOLD, //挂起状态EXEC, //运行状态TERM, //终止状态READY, //就绪状态EXCEPTION //异常状态};private:///协程IDuint64_t m_id = 0;///用户栈大小uint32_t m_stack_size = 0;///协程状态State m_state = INIT;///协程携带的程序上下文ucontext_t m_ctx;///用户栈起始void *m_stack = nullptr;///协程执行的回调函数std::function<void()> m_cb;};
** 配置项
1). 记录协程信息的线程局部变量
/*** @brief 协程ID累加器*/static std::atomic<uint64_t> s_cor_id(0);/*** @brief 当前线程下存在协程的总数*/static std::atomic<uint64_t> s_cor_sum(0);/*** @brief 当前线程下正在运行协程*/static thread_local Coroutine* cor_this = nullptr;/*** @brief 上一次切出的协程*/static thread_local Coroutine::ptr init_cor_sp = nullptr;
2). 协程栈信息
/*** @brief 配置项 每个协程的栈默认大小为1MB*/static ConfigVar<uint32_t>::ptr g_cor_stack_size =Config::LookUp("coroutine.stack_size", (uint32_t)1024*1024, "coroutine stack size");/*** @brief 协程栈内存分配器类*/class MallocStackAllocator{public:/*** @brief 分配内存* @param[in] size 所需内存大小* @return void**/static void* Alloc(size_t size){return malloc(size);}/*** @brief 释放内存* @param[in] vp 栈空间指针* @param[in] size 栈空间大小*/static void Dealloc(void *vp, size_t size){free(vp);}};//使用using起别名using StackAllocator = MallocStackAllocator;
1.2 接口
1.2.1 构造函数
/*** @brief 协程类构造函数* @param[in] cb 指定的执行函数* @param[in] stack_size 协程栈空间大小* @param[in] use_call 是否作为调度协程使用*/Coroutine(std::function<void()> cb, size_t stack_size = 0, bool use_call = false);Coroutine::Coroutine(std::function<void()> cb, size_t stack_size, bool use_call):m_id(++s_cor_id), m_cb(cb){++s_cor_sum;//为协程分配栈空间 让回调函数在对应栈空间去运行m_stack_size = stack_size ? stack_size : g_cor_stack_size->getValue();m_stack = StackAllocator::Alloc(m_stack_size);if(getcontext(&m_ctx) < 0){KIT_LOG_ERROR(g_logger) << "Cortione: getcontext error";KIT_ASSERT2(false, "getcontext error");}//指定代码序列执行完毕后 自动跳转到的指定地方m_ctx.uc_link = nullptr;m_ctx.uc_stack.ss_sp = m_stack;m_ctx.uc_stack.ss_size = m_stack_size;//use_call 标识当前的协程是否是调度协程if(!use_call)//指定要运行的代码序列makecontext(&m_ctx, &Coroutine::MainFunc, 0);elsemakecontext(&m_ctx, &Coroutine::CallMainFunc, 0);KIT_LOG_DEBUG(g_logger) << "协程构造:" << m_id;}
** 私有的默认构造函数
功能:为init协程的生成而准备,生成线程下的第一个协程。
/*** @brief 协程类默认构造函数 负责生成init协程*/Coroutine();Coroutine::Coroutine(){m_state = State::EXEC;SetThis(this);if(getcontext(&m_ctx) < 0){KIT_LOG_ERROR(g_logger) << "Cortione: getcontext error";KIT_ASSERT2(false, "getcontext error");}++s_cor_sum;}
1.2.2 析构函数
/*** @brief 协程类析构函数*/~Coroutine();Coroutine::~Coroutine(){--s_cor_sum;if(m_stack){//只要不是运行态 或者 挂起就释放栈空间KIT_ASSERT(m_state != State::EXEC || m_state != State::HOLD);//释放栈空间StackAllocator::Dealloc(m_stack, m_stack_size);KIT_LOG_DEBUG(g_logger) << "协程析构:" << m_id;}else //没有栈是主协程{KIT_ASSERT(!m_cb);KIT_ASSERT(m_state == State::EXEC);Coroutine* cur = cor_this;if(cur == this)SetThis(nullptr);}}
**私有接口
MainFunc()/CallMainFunc()
/*** @brief 一般协程的回调主函数*/static void MainFunc();void Coroutine::MainFunc(){Coroutine::ptr cur = GetThis();KIT_ASSERT(cur);try{cur->m_cb();cur->m_cb = nullptr;cur->m_state = State::TERM; //协程已经执行完毕。}catch(const std::exception &e){cur->m_state = State::EXCEPTION;KIT_LOG_ERROR(g_logger) << "Coroutine: MainFunc exception:" << e.what()<< std::endl<< BackTraceToString();}catch(...){cur->m_state = State::EXCEPTION;KIT_LOG_ERROR(g_logger) << "Coroutine: MainFunc exception:" << ",but dont konw reason"<< std::endl<< BackTraceToString();}auto p = cur.get();cur.reset(); //让其减少一次该函数调用中应该减少的引用次数p->swapOut();//不会再回到这个地方 回来了说明有问题KIT_ASSERT2(false, "never reach here!");}/*** @brief 持有调度器协程的回调主函数*/static void CallMainFunc();void Coroutine::CallMainFunc(){Coroutine::ptr cur = GetThis();KIT_ASSERT(cur);try{cur->m_cb();cur->m_cb = nullptr;cur->m_state = State::TERM; //协程已经执行完毕。}catch(const std::exception &e){cur->m_state = State::EXCEPTION;KIT_LOG_ERROR(g_logger) << "Coroutine: MainFunc exception:" << e.what()<< std::endl<< BackTraceToString();}catch(...){cur->m_state = State::EXCEPTION;KIT_LOG_ERROR(g_logger) << "Coroutine: MainFunc exception:" << ",but dont konw reson"<< std::endl<< BackTraceToString();}auto p = cur.get();cur.reset(); //让其减少一次该函数调用中应该减少的引用次数p->back();//不会再回到这个地方 回来了说明有问题KIT_ASSERT2(false, "never reach here!");}
1.2.3 程序上下文切换接口 (核心)
核心函数:利用swapcontext(参数1, 参数2),将目标代码段(参数2)推送到CPU上执行,将当前执行的代码段保存起来(保存到参数1)
1). swapIn()
母协程init——————————>子协程
/*** @brief init------>子协程*/void swapIn();void Coroutine::swapIn(){//将当前的子协程Coroutine * 设置到 cor_this中 表明是这个协程正在运行SetThis(this);//没在运行态才能 调入运行KIT_ASSERT(m_state == State::INIT || m_state == State::HOLD);m_state = State::EXEC;if(swapcontext(&init_cor_sp->m_ctx, &m_ctx) < 0){KIT_LOG_ERROR(g_logger) << "swapIn: swapcontext error";KIT_ASSERT2(false, "swapcontext error");}}
2). swapOut()
子协程——————————>母协程init
/*** @brief 子协程------>init*/void swapOut();void Coroutine::swapOut(){//将母协程init_cor_sp 设置到 cor_this中 表明是这个协程正在运行SetThis(init_cor_sp.get());if(swapcontext(&m_ctx, &Scheduler::GetMainCor()->m_ctx) < 0){KIT_LOG_ERROR(g_logger) << "swapOut: swapcontext error";KIT_ASSERT2(false, "swapcontext error");}}
BUG修正1:测试时发生bad_function_call的异常抛出,重新修改调度逻辑
原因:由于要将主线程也加入到工作队列中,从主线程出发的协程切换出去到切换回来的地方不是对应应该切回去的地方,如图:
- 逻辑错误点:在
Coroutine::MainFunc()中的swapOut()究竟切回到哪个地方,逻辑混乱了。

对
swapOut()修改如下:void Coroutine::swapOut(){//如果当前不在调度协程上执行代码 说明是从调度协程切过来的 要切回调度协程if(this != Scheduler::GetMainCor()){SetThis(Scheduler::GetMainCor());if(swapcontext(&m_ctx, &Scheduler::GetMainCor()->m_ctx) < 0){KIT_LOG_ERROR(g_logger) << "swapOut: swapcontext error";KIT_ASSERT2(false, "swapcontext error");}}else //如果当前在调度协程上执行代码 说明是从init协程切过来的 要切回init协程{SetThis(init_cor_sp.get());if(swapcontext(&m_ctx, &init_cor_sp->m_ctx) < 0){KIT_LOG_ERROR(g_logger) << "swapOut: swapcontext error";KIT_ASSERT2(false, "swapcontext error");}}}
BUG修正2:上述的调度逻辑错误源于从
init协程切出还是从调度协程切出于是将从不同两个协程出发的切换函数单独的封装,因为来自
init协程的切换较少,来自调度协程的切换较多。让一组函数负责init协程的切换;另外一组函数负责调度协程的切换
1.2.3.1call()/back()负责init协程
//从init协程 切换到 目标代码void Coroutine::call(){SetThis(this);m_state = State::EXEC;//应该是把当前创建调度器的那个协程的上下文拿出来运行//if(swapcontext(&init_cor_sp->m_ctx, &m_ctx) < 0)if(swapcontext(&init_cor_sp->m_ctx, &m_ctx) < 0){KIT_LOG_ERROR(g_logger) << "call: swapcontext error";KIT_ASSERT2(false, "swapcontext error");}}// 目标代码 切换到 从init协程void Coroutine::back(){SetThis(init_cor_sp.get());if(swapcontext(&m_ctx, &init_cor_sp->m_ctx) < 0){KIT_LOG_ERROR(g_logger) << "back: swapcontext error";KIT_ASSERT2(false, "swapcontext error");}}
1.2.3.2 swapIn()/swapOut()负责调度协程
//从调度器 切换到 到目标代码序列void Coroutine::swapIn(){//将当前的子协程Coroutine * 设置到 cor_this中 表明是这个协程正在运行SetThis(this);//没在运行态才能 调入运行KIT_ASSERT(m_state == State::INIT || m_state == State::HOLD);m_state = State::EXEC;if(swapcontext(&Scheduler::GetMainCor()->m_ctx, &m_ctx) < 0){KIT_LOG_ERROR(g_logger) << "swapIn: swapcontext error";KIT_ASSERT2(false, "swapcontext error");}}//从目标代码序列切换到调度器void Coroutine::swapOut(){SetThis(Scheduler::GetMainCor());if(swapcontext(&m_ctx, &Scheduler::GetMainCor()->m_ctx) < 0){KIT_LOG_ERROR(g_logger) << "swapOut: swapcontext error";KIT_ASSERT2(false, "swapcontext error");}}
1.2.3.3 协程构造函数中要标识当前协程是否是调度协程use_call
调度器协程要执行CallMainFunc();普通协程要执行MainFunc()

1.2.3.4 对应的协程的回调函数MainFunc()也要封装两套,静态成员函数复用原来的代码不太方便
void Coroutine::MainFunc():

void Coroutine::CallMainFunc():

1.2.4 reset()
功能:协程重置,重新指定执行函数。协程状态回到初始状态INIT
/*** @brief 协程重置 重新指定执行函数* @param[in] cb 新指定的执行函数*/void reset(std::function<void()> cb);void Coroutine::reset(std::function<void()> cb){KIT_ASSERT(m_stack);KIT_ASSERT(m_state == State::INIT || m_state == State::TERM ||m_state == State::EXCEPTION);if(getcontext(&m_ctx) < 0){KIT_LOG_ERROR(g_logger) << "reset: getcontext error";KIT_ASSERT2(false, "getcontext error");}m_cb = cb;m_ctx.uc_link = nullptr;m_ctx.uc_stack.ss_sp = m_stack;m_ctx.uc_stack.ss_size = m_stack_size;makecontext(&m_ctx, &Coroutine::MainFunc, 0);m_state = State::INIT;}
1.2.5 Init()
功能:初始化母协程init,为线程创建第一个协程。
/*** @brief 初始化母协程init*/static void Init();void Coroutine::Init(){//创建母协程initCoroutine::ptr main_cor(new Coroutine);KIT_ASSERT(cor_this == main_cor.get());//这句代码很关键init_cor_sp = main_cor;}
1.2.6 YieldToReady()
功能:当前协程让出执行权,并置为就绪状态READY
/*** @brief 当前协程让出执行权,并置为就绪状态READY*/static void YieldToReady();void Coroutine::YieldToReady(){Coroutine::ptr cur = GetThis();KIT_ASSERT(cur->m_state == State::EXEC);cur->m_state = State::READY;cur->swapOut();}
1.2.7 YieldToHold()
功能:当前协程让出执行权,并置为挂起状态HOLD
/*** @brief 当前协程让出执行权,并置为就绪状态HOLD*/static void YieldToHold();void Coroutine::YieldToHold(){Coroutine::ptr cur = GetThis();KIT_ASSERT(cur->m_state == State::EXEC);cur->m_state = State::HOLD;cur->swapOut();}
1.2.8 其他常用接口
/*** @brief 获取协程ID* @return uint64_t*/uint64_t getID() const {return m_id;}/*** @brief 获取协程运行状态* @return State*/State getState() const {return m_state;}/*** @brief 设置协程状态* @param[in] state*/void setState(State state) {m_state = state;}/*** @brief 给当前线程保存正在执行的协程this指针* @param[in] c 正在运行的协程this指针*/static void SetThis(Coroutine *c);void Coroutine::SetThis(Coroutine *c){cor_this = c;}/*** @brief 返回当前在执行的协程的this智能指针* @return Coroutine::ptr*/static Coroutine::ptr GetThis();Coroutine::ptr Coroutine::GetThis(){if(cor_this){return cor_this->shared_from_this();}Init();return cor_this->shared_from_this();}/*** @brief 获取当前线程上存在的协程总数* @return uint64_t*/static uint64_t TotalCoroutines();uint64_t Coroutine::TotalCoroutines(){return s_cor_sum;}/*** @brief 获取协程ID* @return uint64_t*/static uint64_t GetCoroutineId();uint64_t Coroutine::GetCoroutineId(){if(cor_this){return cor_this->getID();}return 0;}
2. 协程调度
实现目标:实现跨线程间的协程切换。让A线程中的1号协程切换到B线程中的3号协程上去执行对应的任务。即:线程间从任务队列”抢”任务,抢到任务之后以协程为目标代码载体,使用同步切换的方式到对应的目标代码上进行执行。
非常非常注意:采用ucontext的API,如果程序上下文衔接不恰当,会导致最后一个协程退出是时候,整个主线程也退出了,这是相当危险的!!!
实现调度器schedule
分配有多个线程,一个线程又有分配多个协程。 N个线程对M个协程。
- schedule 是一个线程池,分配一组线程。
- schedule 是一个协程调度器,分配协程到相应的线程去执行目标代码
- 方式一:协程随机选择一个空闲的任意的线程上执行
- 方式二:给协程指定一个线程去执行
2.1 基本的调度思路

2.2 成员变量
class Schduler{......protected:/// 线程ID数组std::vector<int> m_threadIds;/// 总共线程数size_t m_threadSum;/// 活跃线程数std::atomic<size_t> m_activeThreadCount = {0};/// 空闲线程数std::atomic<size_t> m_idleThreadCount = {0};/// 主线程IDpid_t m_mainThreadId = 0;/// 正在停止运行标志bool m_stopping = true;/// 是否自动停止标志bool m_autoStop = false;private:/// 线程池 工作队列std::vector<Thread::ptr> m_threads;/// 任务队列std::list<CoroutineObject> m_coroutines;/// 互斥锁MutexType m_mutex;/// 主协程智能指针Coroutine::ptr m_mainCoroutine;// 调度器名称std::string m_name;};
*封装一个自定义的可执行对象结构体
目的:让调度器调度执行的对象不仅仅为Coroutine协程体,还可以是一个function<>可调用对象
private:/*** @brief 可执行对象结构体*/struct CoroutineObject{/// 协程Coroutine::ptr cor;/// 函数std::function<void()> cb;/// 指定的执行线程pid_t threadId;CoroutineObject(Coroutine::ptr p, pthread_t t):cor(p), threadId(t){ }CoroutineObject(Coroutine::ptr* p, pthread_t t):threadId(t){//减少一次智能指针引用cor.swap(*p);}CoroutineObject(std::function<void()> f, pthread_t t):cb(f), threadId(t) { }CoroutineObject(std::function<void()> *f, pthread_t t):threadId(t){//减少一次智能指针引用cb.swap(*f);}/*和STL结合必须有默认构造函数*/CoroutineObject():threadId(-1){ }void reset(){cor = nullptr;cb = nullptr;threadId = -1;}};
2.3 接口
2.3.1 构造函数
/*** @brief 调度器类构造函数* @param[in] name 调度器名称* @param[in] threads_size 初始线程数量* @param[in] use_caller 当前线程是否纳入调度队列 默认纳入调度*/Scheduler(const std::string& name = "", size_t threads_size = 1, bool use_caller = true);Scheduler::Scheduler(const std::string& name, size_t threads_size, bool use_caller):m_name(name.size() ? name : Thread::GetName()){KIT_ASSERT(threads_size > 0);//当前线程作为调度线程使用if(use_caller){//初始化母协程 pre_cor_sp 被初始化Coroutine::Init();--threads_size; //减1是因为当前的这个线程也会被纳入调度 少创建一个线程//这个断言防止 该线程中重复创建调度器KIT_ASSERT(Scheduler::GetThis() == nullptr);t_scheduler = this;//新创建的主协程会参与到协程调度中m_mainCoroutine.reset(new Coroutine(std::bind(&Scheduler::run, this), 0, true));//线程的主协程不再是一开始使用协程初始化出来的那个母协程,而应更改为创建了调度器的协程t_sche_coroutine = m_mainCoroutine.get();m_mainThreadId = GetThreadId();m_threadIds.push_back(m_mainThreadId);}else //当前线程不作为调度线程使用{m_mainThreadId = -1;}//防止线程名称没改Thread::SetName(m_name);m_threadSum = threads_size;}
2.3.2 析构函数
/*** @brief 调度器类析构函数*/virtual ~Scheduler();Scheduler::~Scheduler(){//只有正在停止运行才能析构KIT_ASSERT(m_stopping);if(Scheduler::GetThis() == this){t_scheduler = nullptr;}}
2.3.3 scheduler大概几个核心的接口
start()开启调度器运作stop()停止调度器运作run()这个函数真正执行调度逻辑schduleNoLock()将任务加进队列
下面几个接口主要实现在派生类中,父类中不作核心实现:
tickle()线程唤醒stopping()线程清理回收idle()协程没有任务可做时的处理,借助epoll_wait来唤醒有任务可执行
1). run()
两个部分在执行该函数:一部分是负责在线程里处理调度工作的主协程 ,一部分是线程池的其他子线程
功能:负责协程调度和线程管理,从任务队列拿出任务,执行对应的任务。
- 核心逻辑:
while(1)
{
加锁,取出可执行对象容器/消息队列/任务队列
m_couroutine中的元素,解锁如果当前的可执行对象没有指定线程 且不是 当前在跑的线程要执行的,就跳过。并且设置一个信号量,如
bool is_tickle以便通知其他线程来执行这个属于它们的可执行对象(任务)如果当前的可执行对象是当前在跑的线程要执行的,检查协程体和回调函数是否为空,为空断言报错;不为空取出,从队列删除该元素
如果没有一个可执行对象是当前跑的线程应该执行的,就设置一个标志
bool is_work表明当前是否有任务可做,没有转去执行idle()函数
开始执行从队列中拿出的可执行对象,分为:协程和函数。(本质都是要调度协程,只是兼容传入的可执行对象是函数的情况)
如果为协程,并且当前线程应该工作
is_work = true,分情况讨论:- 协程处于没有执行完毕
TERM且没有异常EXCEPTION,就swapIn()调入(继续)执行。调回(不一定是执行完毕了,也有可能到时了)后,如果处于就绪状态READY需要再一次加入队列中; - 否则,调回后仍处于没有执行完毕
TERM且没有异常EXCEPTION就要将其置为挂起HOLD状态。
- 协程处于没有执行完毕
如果为函数,整个流程和协程一模一样,只是需要使用一个指针创建一个协程使其能够被调度。
}
void Scheduler::run(){KIT_LOG_DEBUG(g_logger) << "run start!";setThis();//当前线程ID不等于主线程IDif(GetThreadId() != m_mainThreadId){t_sche_coroutine = Coroutine::GetThis().get();}//创建一个专门跑idel()的协程Coroutine::ptr idle_coroutine(new Coroutine(std::bind(&Scheduler::idle, this)));Coroutine:: ptr cb_coroutine;CoroutineObject co;while(1){/* 一、从消息队列取出可执行对象 *///清空可执行对象co.reset();//是一个信号 没轮到当前线程执行任务 就要发出信号通知下一个线程去处理bool is_tickle = false;bool is_work = true;//加锁{//取出协程消息队列的元素MutexType::Lock lock(m_mutex);auto it = m_coroutines.begin();for(;it != m_coroutines.end();++it){//a.当前任务没有指定线程执行 且 不是我当前线程要处理的协程 跳过if(it->threadId != -1 && it->threadId != GetThreadId()){is_tickle = true;continue;}KIT_ASSERT(it->cor || it->cb);//b.契合线程的协程且正在处理 跳过// if(it->cor && it->cor->getState() == Coroutine::State::EXEC)// {// continue;// }//b.是我当前线程要处理的任务/协程 就取出并且删除co = *it;m_coroutines.erase(it);++m_activeThreadCount;break;}// KIT_LOG_DEBUG(g_logger) << "m_coroutine size=" << m_coroutines.size();if(it == m_coroutines.end()){is_work = false;}else{KIT_LOG_DEBUG(g_logger) << "拿到一个任务";}}//解锁if(is_tickle){tickle();}/*二、根据可执行对象的类型 分为 协程和函数 来分别执行对应可执行操作*///a. 如果要执行的任务是协程//契合当前线程的协程还没执行完毕if(co.cor && is_work && co.cor->getState() != Coroutine::State::TERM &&co.cor->getState() != Coroutine::State::EXCEPTION){co.cor->swapIn();--m_activeThreadCount;//从上面语句调回之后的处理 分为 还需要继续执行 和 需要挂起if(co.cor->getState() == Coroutine::State::READY){schedule(co.cor);}else if(co.cor->getState() != Coroutine::State::TERM &&co.cor->getState() != Coroutine::State::EXCEPTION){//协程状态置为HOLDco.cor->setState(Coroutine::State::HOLD);}//可执行对象置空co.reset();}else if(co.cb && is_work) //b. 如果要执行的任务是函数{//KIT_LOG_DEBUG(g_logger) << "任务是函数";if(cb_coroutine) //协程体的指针不为空就继续利用现有空间{cb_coroutine->reset(co.cb);}else //为空就重新开辟{cb_coroutine.reset(new Coroutine(co.cb));}//可执行对象置空co.reset();cb_coroutine->swapIn();--m_activeThreadCount;//从上面语句调回之后的处理 分为 还需要继续执行 和 需要挂起if(cb_coroutine->getState() == Coroutine::State::READY){schedule(cb_coroutine);//智能指针置空cb_coroutine.reset();}else if(cb_coroutine->getState() == Coroutine::State::TERM ||cb_coroutine->getState() == Coroutine::State::EXCEPTION){//把执行任务置为空cb_coroutine->reset(nullptr);}else{//状态置为 HOLDcb_coroutine->setState(Coroutine::State::HOLD);//智能指针置空cb_coroutine.reset();}}else //c.没有任务需要执行 去执行idle() --->代表空转{//负责idle()的协程结束了 说明当前线程也结束了直接breakif(idle_coroutine->getState() == Coroutine::State::TERM){KIT_LOG_INFO(g_logger) << "idle_coroutine TERM!";break;}++m_idleThreadCount;idle_coroutine->swapIn();--m_idleThreadCount;if(idle_coroutine->getState() != Coroutine::State::TERM &&idle_coroutine->getState() != Coroutine::State::EXCEPTION){//状态置为 HOLDidle_coroutine->setState(Coroutine::State::HOLD);}}}}
2). start()
功能:开启Schuduler调度器的运行。根据传入的线程数,初始化其余子线程,将调度协程推送到CPU
//开启调度器void Scheduler::start(){MutexType::Lock lock(m_mutex);//一开始 m_stopping = trueif(!m_stopping){KIT_LOG_WARN(g_logger) << "Scheduler: scheduler is stopping!";return;}m_stopping = false;KIT_ASSERT(m_threads.empty());m_threads.resize(m_threadSum);for(size_t i = 0;i < m_threads.size();++i){m_threads[i].reset(new Thread(std::bind(&Scheduler::run, this), m_name + "_" + std::to_string(i)));m_threadIds.push_back(m_threads[i]->getId());}lock.unlock();if(m_mainCoroutine)m_mainCoroutine->call();}
3). stop()
功能:停止Scheduler调度器运行。分情况讨论:
只有一个线程(即:主线程/调度协程在运行),并且调度协程处于终止态或创建态。直接调
stopping()负责清理、回收工作,退出返回。有多个线程(是一组线程池),先设置标志位
m_stopping,唤醒tickle()其他子线程根据该标志位退出;都完毕之后,再将调度协程唤醒退出。
//调度器停止void Scheduler::stop(){/** 用了use_caller的线程 必须在这个线程里去执行stop* 没有用use_caller的线程 可以任意在别的线程执行stop*/m_autoStop = true;//1.只有一个主线程在运行的情况 直接停止即可if(m_mainCoroutine && m_threadSum == 0 &&(m_mainCoroutine->getState() == Coroutine::State::TERM ||m_mainCoroutine->getState() == Coroutine::State::INIT)){KIT_LOG_INFO(g_logger) << this << ",scheduler name=" << m_name << " stopped";m_stopping = true;if(stopping())return;}//2.多个线程在运行 先把子线程停止 再停止主线程//主线程Id不为-1说明是创建调度器的线程if(m_mainThreadId != -1){//当前的执行器要把创建它的线程也使用的时候 它的stop一定要在创建线程中执行KIT_ASSERT(GetThis() == this);}else{KIT_ASSERT(GetThis() != this);}//其他线程根据这个标志位退出运行m_stopping = true;//唤醒其他线程结束for(size_t i = 0;i < m_threadSum;++i){tickle();}//最后让主线程也退出if(m_mainCoroutine){tickle();}if(stopping())return;}
4). scheduleNoLock()
功能:将任务加入到任务队列中。接收参数形式:协程Coroutine和函数对象function<>。多封装了一层用于处理单个加入队列和批量加入队列的情况。
- 核心逻辑:

//添加任务函数 单个放入队列template<class CorOrCB>void schedule(CorOrCB cc, int threadId = -1){bool isEmpty = false;{MutexType::Lock lock(m_mutex);isEmpty = scheduleNoLock(cc, threadId);}if(isEmpty)tickle();}//添加任务函数 批量放入队列template<class InputIterator>void schedule(InputIterator begin, InputIterator end){bool isEmpty = false;{MutexType::Lock lock(m_mutex);while(begin != end){//只要有一次为真 就认为之前经历了空队列 必然有休眠 就必然要唤醒isEmpty = scheduleNoLock((&(*begin))) || isEmpty;++begin;}}if(isEmpty)tickle();}//添加任务函数 真正执行添加动作template<class CorOrCB>bool scheduleNoLock(CorOrCB cc, int threadId = -1){//如果为 true 则说明之前没有任何任务需要执行 现在放入一个任务bool isEmpty = m_coroutines.empty();CoroutineObject co(cc, threadId);if(co.cor || co.cb){m_coroutines.push_back(co);}return isEmpty;}
C++知识点补充复习:std::bind()函数适配器
出处《C++ Primer》 P354
作用:接收一个可调用对象将其转换为一个我们需要的合适的可调用对象,不破坏原有对象的参数列表。
通俗的理解:可以事先将原有的可调用对象的参数进行一些指定(绑定),以符合当前需求场景。
本质上:bind生成的可调用对象会去调用所接受的对象,并且自动根据之前绑定好的参数自动传参
class A { public: void test(int a, int b) { cout << a + b << endl; }
static test2(int a, int b){cout << a + b << endl;}void func(){//普通成员函数需要在第一个参数位置传入this指针auto f1 = std::bind(&A::test, this, 1, 2);f1();//静态成员函数不需要传this指针auto f2 = std::bind(&A::test2, 1, 2);f2();}
};
void test(int a, int b) { cout << a + b << endl; }
int main() {
auto f1 = std::bind(&test, 1, 2);auto f2 = std::bind(&test, std::placeholders::_1, 2);auto f3 = std::bind(&test, std::placeholders::_1, std::placeholders::_2);f1();f2(2);f3(1, 2);return 0;
}
- **最先用于解决算法模板**`**algorithm**`**中的一些问题:以**`**find_if**`**算法为例子**假设我们需要找出一堆字符串中大于某一个长度sz的字符串,使用`find_if`算法模板如下:```cpp#include <functional>#include <vector>#include <string>#include <algorithm>int main(){vector<string> mv = {"ASD","sdassdfsdfd","w21eeff1","sadawqq1"};int sz = 4;auto it = find_if(mv.begin(), mv.end(), [sz](string& a){return a.size() > sz;});cout << "第一个大于sz=" << sz << "的字符串是:" << *it << endl;return 0;}

有了函数适配器则不需要lambda表达式去作捕获:
#include <iostream>#include <functional>#include <vector>#include <string>#include <algorithm>bool func(string &a, int sz){return a.size() > sz;}int main(){vector<string> mv = {"ASD","sdassdfsdfd","w21eeff1","sadawqq1"};int sz = 4;auto it = find_if(mv.begin(), mv.end(), std::bind(&func, std::placeholders::_1, 4));cout << "第一个大于sz=" << sz << "的字符串是:" << *it << endl;return 0;}

- 值得注意的一个问题:当类内出现函数重载,又要结合bind函数的情况:
需要显式的将类成员函数指针指示出来,来区别不同的重载函数
//错误写法:class A{public:void test(int a, int b){cout << a + b << endl;}static void test(int a, int b, int c){cout << a + b << endl;}void func(){//由于函数同名,不知道需要绑定哪一个auto f1 = std::bind(&A::test, this, 1, 2);auto f2 = std::bind(&A::test, 1, 2, 3);f1();f2();}};
//正确写法class A{public:void test(int a, int b){cout << a + b << endl;}static void test(int a, int b, int c){cout << a + b << endl;}void func(){auto f1 = std::bind((void (A::*)(int,int))&A::test, this, 1, 2);auto f2 = std::bind((void (*)(int, int, int))&A::test, 1, 2, 3);f1();f2();}};
