Hey, I've been working on a coroutine library for NodeJS recently and I
think I could make everything a lot smoother with some changes to v8, but
first I wanted to check in with the dev team to see what the best way to
approach this problem is, or if this would even be a welcome change or not.

Basically my library provides a way to spawn coroutines in Javascript code
so that users can write asynchronous code in a synchronous style using
cooperative multitasking. Each coroutine allocates a chuck of memory on the
heap and jumps into that as a new stack. This is all handled by POSIX
ucontext.

The problem, however, is that there's no way to communicate to v8 that I'm
on a new stack. So when the garbage collector kicks in it starts climbing up
a stack that it has no idea about and all hell breaks loose. I've solved
this problem in my extension with some terrible black magic (LD_PRELOAD to
override pthread_* and trick v8 into thinking each coroutine is a new
thread). While effective and surprisingly stable it's not totally desirable.
I'd like a solution that doesn't force me to hook core OS libraries. If
you're curious you can see this on github:
https://github.com/laverdet/node-fibers/blob/master/src/coroutine.cc

What I'd like to do is add some kind of optional parameter to Locker which
would override v8's use of thread locals and pthread_self() and instead read
stack-specific information straight from the client (in an opaque handle of
course).

Essentially I want to be able to do something like this in client code:

    void my_v8_function() {
      v8::Locker locker;
      // Use v8 here
      {
        v8::Unlocker locker;
        run_coroutine();
      }
      // Continue using v8 here
    }

    void run_coroutine() {
      // Please pretend that this is on a new stack, but the same thread
      v8::Handle<v8::UserStackLock> lock = v8::UserStackLock::New();
      v8::Locker locker(lock);
      // Use v8 here
      resume_previous_coroutine();
    }

Would this be a reasonable API? I can't really think of any valid use cases
for the API other than mine, but then again it's a fairly unique problem. I
guess an alternative would be to land my Fiber class in v8 proper, but it's
not standard Javascript by any means. Plus I don't really want to add
support for all the different platforms v8 supports. Doing it this way is
the minimum amount of changes I'd need to make to enable coroutines in v8.
The surface area should be relatively small, mostly isolated to
v8threads.cc.

I know there's been some discussion on this in the past--
Malcolm Handley recommends using threads to simulate coroutines, but then
I'm giving up many of the advantages of using coroutines in the first place.
http://groups.google.com/group/v8-users/browse_thread/thread/0dc2566b93667ac2

Thanks for any insight!

-- 
v8-dev mailing list
[email protected]
http://groups.google.com/group/v8-dev

Reply via email to