#209·libco

如果由 CO_ROUTINE_SPECIFIC 定义的变量在多个 cpp 中被引用,则在发布构建过程中会生成多个该变量的实例

作者: sunjinopensource创建于 2024年1月4日更新于 2025年10月1日

specific_data.h

#pragma once #include "co_routine_specific.h" struct CoSd { int idx; }; void PrintData(const char* co_name); void* Co2Func(void* args); CO_ROUTINE_SPECIFIC(CoSd, __cosd);

specific_data.cc

#include "specific_data.h" #include #include "co_routine.h" void* Co2Func(void* args) { __cosd->idx = 2; while (true) { PrintData((const char*)args); co_poll(co_get_epoll_ct(), NULL, 0, 1000); } return NULL; } void PrintData(const char* co_name) { printf("%s with specific data idx = %d\n", co_name, __cosd->idx); }

main.cc

#include #include "co_routine.h" #include "specific_data.h" void* Co1Func(void* args) { __cosd->idx = 1; while (true) { PrintData((const char*)args); co_poll(co_get_epoll_ct(), NULL, 0, 1000); } return NULL; } int main() { stCoRoutine_t* co1; co_create(&co1, NULL, Co1Func, (void*)"co1"); co_resume(co1);

stCoRoutine_t* co2; co_create(&co2, NULL, Co2Func, (void*)"co2"); co_resume(co2);

co_eventloop(co_get_epoll_ct(), NULL, NULL); return 0; }

释放版本下的输出

co1 with specific data idx = 0
co2 with specific data idx = 2
co1 with specific data idx = 0
co2 with specific data idx = 2
...
### 调试版本下的输出

co1 with specific data idx = 1 co2 with specific data idx = 2 co1 with specific data idx = 1 co2 with specific data idx = 2 ...