concurrent/parallel processing in lua #494
-
I have some doubts about how to enable Lua code to achieve concurrent/parallel processing ability through asynchronous methods provided by Rust in mlua. Here is my test code, where I believe the implementation of the asynchronous method
First, I tried
Since I used the multi_thread mode of the tokio runtime, the printed thread id information shows different threads, which is as expected. Later, I saw:
This means that for multi-threaded parallelism, due to the locking mechanism, it might not achieve the desired effect.
Currently, both approaches are feasible. My question is, assuming my asynchronous tasks are ideal, is the second approach more efficient because, as I understand it, mlua itself is inherently not thread-safe? Any suggestions and discussions are welcome. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
In both options you will achieve similar level of concurrency. In The However, to achieve true parallelism (i.e. ability to run Lua code in parallel; without depending on yielding points) you would need to run many Lua VMs (ideally one per thread) to use them in parallel. |
Beta Was this translation helpful? Give feedback.
In both options you will achieve similar level of concurrency. In
send
mode the lock is released when a Future returnsPending
which allow to schedule many futures (task_fn.call_async
) concurrently.The
LocalSet
approach is more efficient simply because it's lock-free. From the tokio perspective and from Lua perspective as well.However, to achieve true parallelism (i.e. ability to run Lua code in parallel; without depending on yielding points) you would need to run many Lua VMs (ideally one per thread) to use them in parallel.
You can pass data between VMs using serialization or by sharing memory (e.g. a userdata object like
Arc<Mutex<HashMap<K, V>>>
) that can be safely accessed by all VMs.