Boost.coroutine unidirectional: Legal to get reference to stack variable on suspension?

StackOverflow https://stackoverflow.com/questions/22110432

  •  18-10-2022
  •  | 
  •  

Domanda

I would like to know if when resuming a coroutine that did not finish yet it is legal to get a reference to one of the variables in its stack from outside the couroutine.

Like this:

coroutine<void>::pull_type myclass::my_func() {
  auto coro = [this](coroutine<void>::push_type & sink) {
     auto myvar = 25;
     this->do_something_with_my_var_by_ref_when_suspended(myvar);
     sink();
     while (1) {
        //...
        sink();
     }
  };
}

auto coro = this->myfunc();
//Here myvar from coro is being used but coro is suspended.
//Will myvar be valid? coro is not finished yet.
this->do_something_with_myvar_when_coro_suspended();

Thanks for your time

È stato utile?

Soluzione 2

So I did myself a small program. It seems to prove that this is working correctly in the case I asked, but I still cannot figure out why it does strange things in other code I have.

#include <boost/coroutine/all.hpp>

using namespace boost::coroutines;

int * g_i = nullptr;

coroutine<void>::pull_type
my_func() {
   coroutine<void>::pull_type coro(
     [](coroutine<void>::push_type & suspend_coro) {
       int i = 7;
       g_i = &i;
       suspend_coro();
       ++i;
       g_i = &i;
       suspend_coro();
  });

   return coro;
}


int main(int argc, char * argv[]) {
   auto coro = my_func();
   std::cout << *g_i << std::endl;
   coro();
   std::cout << *g_i << std::endl;
}

Prints 7 and 8.

Altri suggerimenti

coroutines are moeveable only - you need to return coro at the end of my_func().

In general myvar is allocated on coroutine's stack and you can pass an reference or pointer to arbitrary functions in your application (address of memory location of myvar). unless the stack is unwound (or at least the stack frame containing myvar) it is vaild.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top