Den 13. apr. 2010 14.12 skrev Reko Tiira <[email protected]>: > Hey, > > I want to embed V8 in my game engine, mainly because I prefer it's C++ > API over that of SpiderMonkey's. However I'm having some thoughts > about thread-safety, since my engine would be executing each script in > its own thread. > > I know that only a single thread can use V8 at a time, and that you > use the v8::Locker to lock access to V8 per-thread basis. This is all > good for me, because I can still unlock the thread if I have to wait > for some resource that is not related to V8. For sake of simplicity, > let's say I have to sleep for 2 seconds in a script, I could do this > by: > > { > v8::Unlocker ul; > Sleep(2); > } > > And while the thread sleeps, other scripts could still execute since > v8 is unlocked. However what I'm concerned about is how will > HandleScopes scope with this. Consider the following example: > > { > v8::Locker l; > v8::HandleScope handle_scope; > > { > v8::Unlocker ul; > Sleep(2); > } > > v8::Local<v8::Value> str = v8::String::New("foobar"); > > // For sake of not having to write almost two identical functions, > // assume that ONLY thread 1 does this: > { > v8::Unlocker ul; > Sleep(2); > } > std::string s = String::AsciiValue ascii(str); > > // And thread 2 would ONLY do this: > return; > } > > Let's say that two threads run this same script. When the first thread > unlocks for the first time and goes to sleep, the 2nd thread will > create a new HandleScope, and thus all consecutive allocations are > done on the 2nd thread's handle scope. So when thread 2 goes to sleep, > and thread 1 wakes up, it'll create a new String using the HandleScope > that was created on the thread 2 while thread 1 was sleeping. Now >
No, this case is taken care of. The Locker and Unlocker objects make sure to activate the right handle scopes, so when thread 1 wakes up, the allocation takes place with the correct HandleScope. > thread 1 will go to sleep again, and thread 2 will wake up. At this > point thread 2 simply returns, and since the HandleScope goes out of > scope, it'll free all the locals that it had allocated, _including_ > the string created in thread 1 (since it was allocated using the wrong > HandleScope). After this the control returns back to the thread 1, > which tries to use the already de-allocated value, and probably crash > because of that. > > Am I getting this right? If I am, is there any plausible way to get > around this, because I really need to be able to run multiple scripts > at the same time, but I have plenty of scripts that would block until > some sort of an event happens in the game, and other scripts need to > be able to run during the time the script waits. > > Regards, > Reko Tiira > > -- > v8-users mailing list > [email protected] > http://groups.google.com/group/v8-users > -- v8-users mailing list [email protected] http://groups.google.com/group/v8-users To unsubscribe, reply using "remove me" as the subject.
