微信后台phxrpc协程库理解(提取协程相关源码)

305 阅读1分钟

源码来自github.com/Tencent/phx…

我把协程相关的源码提取出来,写了个测试程序(仿造github.com/cloudwu/cor…),便于理解:

看runtime_.Resume(id)这一行,就是执行当前的协程,这个协程在创建的时候被定位到执行关联的函数处,这个具体实现在uthread_context_system.cpp中,所以当runtime_.Resume(id)时候其实就是执行foo函数。

//https://github.com/Tencent/phxrpc
//https://www.jianshu.com/p/4d95eb7af24b

#include "uthread_runtime.h"
#include <functional>

phxrpc::UThreadRuntime *runtime_;

static void foo(int arg) {
    int start = arg;

    for (int i = 0; i < 5; i++)
    {
        printf("coroutine %d : %d\n",  runtime_->GetCurrUThread(), start + i);
        runtime_->Yield();//放弃
    }
}

static void test() {
    int arg1 = { 0 };
    int arg2 = { 100 };

    int co1 = runtime_->Create(std::bind(&foo, arg1), nullptr);
    int co2 = runtime_->Create(std::bind(&foo, arg2), nullptr);

    printf("main start\n");

    while (!runtime_->IsAllDone())
    {
        runtime_->Resume(co1);//执行
        runtime_->Resume(co2);
        printf("GetUnfinishedItemCount:%d\n", runtime_->GetUnfinishedItemCount());
    }

    printf("main end\n");
}

int main(int argc, char *argv[])
{
    runtime_ = new phxrpc::UThreadRuntime(8192, false);

    test();

    delete runtime_;

    return 0;
}

运行结果是:

main start
coroutine 0 : 0
coroutine 1 : 100
GetUnfinishedItemCount:2
coroutine 0 : 1
coroutine 1 : 101
GetUnfinishedItemCount:2
coroutine 0 : 2
coroutine 1 : 102
GetUnfinishedItemCount:2
coroutine 0 : 3
coroutine 1 : 103
GetUnfinishedItemCount:2
coroutine 0 : 4
coroutine 1 : 104
GetUnfinishedItemCount:2
GetUnfinishedItemCount:0
main end

完整的工程下载地址是:download.csdn.net/download/li…

另外推荐一个案例:

coroutine example, using phxrpc coroutine framework, receive data from upstream and set redis, qps 12w

download.csdn.net/download/hi…

 

---

参考文献:

www.jianshu.com/p/4d95eb7af…

github.com/Tencent/lib…

github.com/cloudwu/cor… 云风

github.com/Nickqiaoo/c… 带注释的版本

blog.csdn.net/LMFQYJ/arti…  云风coroutine源码分析

blog.csdn.net/Swartz2015/…  从云风的coroutine库学习协程