源碼來自 https://github.com/Tencent/phxrpc 我把協程相關的源碼提取出來,寫了個測試程式(仿造 https://github.com/cloudwu/coroutine/blob/master/main.c
),便于了解:
看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
完整的工程下載下傳位址是:
https://download.csdn.net/download/libaineu2004/10874580另外推薦一個案例:
coroutine example, using phxrpc coroutine framework, receive data from upstream and set redis, qps 12w
https://download.csdn.net/download/hintonic/10758106---
參考文獻:
https://www.jianshu.com/p/4d95eb7af24b https://github.com/Tencent/libco https://github.com/cloudwu/coroutine/雲風
https://github.com/Nickqiaoo/coroutine帶注釋的版本
https://blog.csdn.net/LMFQYJ/article/details/79211084雲風coroutine源碼分析
https://blog.csdn.net/Swartz2015/article/details/76274688從雲風的coroutine庫學習協程