cesanta / v7

Embedded JavaScript engine for C/C++
Other
1.43k stars 177 forks source link

help: pattern to create/destroy v7 instances? #557

Open benoitc opened 8 years ago

benoitc commented 8 years ago

I am wondering if there is a good pattern to create and destroy multiple instance of v7?

Is this ok to to create/destroy an instance each time we want to execute a function in a job? Can we reuse the instance in different threads? For example maintaining a pool of instance ? Or better to have a pool of workers?

dimonomid commented 8 years ago

Is this ok to to create/destroy an instance each time we want to execute a function in a job?

Yes it's ok; probably not the most efficient way, but it really depends on the application.

Can we reuse the instance in different threads?

v7 is not thread-safe; so, if you need to reuse the same v7 instance in different threads, you must provide proper synchronization.

Or, you might want to have a separate v7 instance for each thread; then, they can work in parallel, but keep in mind that if you have some JS value (v7_val_t) which belongs to the instance A, generally it's illegal to use it in the instance B. And, obviously, if the scripts you execute use some shared resource (e.g. via your custom C-functions), then these C-functions should provide synchronization as well.

mkmik commented 8 years ago

just a clarification/nitpick: you cannot use the same v7 instance concurrently by different threads. You can keep a pool of v7 instances and have a thread use one v7 context for a bit, put it back in the pool and later have another thread use it for a while.

There are some libraries (zeromq springs to my mind) that don't allow you to do that (forcing you to create and use a given context from the same thread), hence the clarification.


Implementation note: currently numbers, booleans, null, undefined and short strings (<=5 chars) are completely stored in the v7_val_t type, so you can pass them between threads (using the usual C synchronisation primitives) and use them in another V7 context.

However relying on this behaviour is unsupported. We might change the underlying implementation at any time. All the v7_val_t values are (potentially) private to a V7 context. We recently changed all the accessors to reflect that potential dependency even for types that currently are not implemented with pointers to context private memory.

double v7_get_double(struct v7 *v7, v7_val_t v);