Skip to content

Commit

Permalink
memory optimization, free some memory in terminated coroutine
Browse files Browse the repository at this point in the history
  • Loading branch information
idealvin committed Nov 1, 2021
1 parent 5ca7266 commit a396b7e
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 7 deletions.
8 changes: 5 additions & 3 deletions src/co/scheduler.cc
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ void SchedulerImpl::stop() {
void SchedulerImpl::main_func(tb_context_from_t from) {
((Coroutine*)from.priv)->ctx = from.ctx;
gSched->running()->cb->run(); // run the coroutine function
gSched->recycle(); // recycle the current coroutine
tb_context_jump(from.ctx, 0); // jump back to the from context
}
Expand Down Expand Up @@ -86,11 +85,14 @@ void SchedulerImpl::resume(Coroutine* co) {
from = tb_context_jump(co->ctx, _main_co); // jump back to where the user called yiled()
}
// yiled() was called in coroutine, the scheduler will jump back to resume()
if (from.priv) {
// yiled() was called in the coroutine, update context for it
assert(_running == from.priv);
_running->ctx = from.ctx; // update context for the coroutine
_running->ctx = from.ctx;
CO_DBG_LOG << "yield co: " << _running << " id: " << _running->id;
} else {
// the coroutine has terminated, recycle it
this->recycle();
}
}
Expand Down
12 changes: 9 additions & 3 deletions src/co/scheduler.h
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ class Copool {

void push(Coroutine* co) {
_ids.push_back(co->id);
if (_ids.size() >= 1024) co->stack.reset();
}

Coroutine* operator[](size_t i) {
Expand Down Expand Up @@ -300,7 +301,10 @@ class SchedulerImpl : public co::Scheduler {
static void main_func(tb_context_from_t from);

// push a coroutine back to the pool, so it can be reused later.
void recycle() { _co_pool.push(_running); }
void recycle() {
_stack[_running->sid].co = 0;
_co_pool.push(_running);
}

// start the scheduler thread
void start() { Thread(&SchedulerImpl::loop, this).detach(); }
Expand All @@ -313,8 +317,10 @@ class SchedulerImpl : public co::Scheduler {

// save stack for the coroutine
void save_stack(Coroutine* co) {
co->stack.clear();
co->stack.append(co->ctx, _stack[co->sid].top - (char*)co->ctx);
if (co) {
co->stack.clear();
co->stack.append(co->ctx, _stack[co->sid].top - (char*)co->ctx);
}
}

// pop a Coroutine from the pool
Expand Down
2 changes: 1 addition & 1 deletion test/nco.cc
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#include "co/co.h"

DEF_uint32(n, 1000000, "coroutine number");
DEF_uint32(t, 7, "seconds to sleep in coroutines");
DEF_uint32(t, 60, "seconds to sleep in coroutines");

DEF_main(argc, argv) {
for (int i = 0; i < FLG_n; ++i) {
Expand Down

0 comments on commit a396b7e

Please sign in to comment.