#209·libco

if a variable defined by CO_ROUTINE_SPECIFIC is referenced in multiple cpps, multiple instances of the variable will be generated under release build

Author: sunjinopensourceCreated Jan 4, 2024Updated Oct 1, 2025

specific_data.h

cpp
#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

cpp
#include "specific_data.h"

#include <cstdio>

#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

cpp
#include <cstdio>

#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;
}

error:output under release build

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

ok:output under debug build

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