I know this is an unusual request, since when integrating VTK in native applications, you have a main thread and asynchronous execution belongs to the application.
None the less.
It is quite simple to extend the SMPTools
API to support a FireAndForget
or event an Async
, which returns a future. For WASM applications, I have tried doing this and then inside the FireAndForget
, I can do For
and at the end of execution, I can schedule a function to be executed on main and wait for a condition variable. The application can then call Invoke
on an event and set the condition variable such that the FireAndForget
finished.
The reason why this is interesting is that for WASM
, VTK
consumes all threads and threads on WASM
behave like physical threads - if there is no resources available, a call to std::thread
will result in a no resources available error.
Another approach would be to add a flag to set the maximum number of threads consumed by VTK and use another C++ thread for the above. What are your thoughts?
If it is something that we could have in the vtkSMPTools
, I could implement it for the other backends:
You would be able to do:
std::atomic<int> counter{ 0 };
for (int i = 0; i < rootTasks; ++i)
{
spsSMPTools::FireAndForget(
[&counter]()
{
// Outer For loop inside a fire-and-forget
vtkSMPTools::For(0, middleTasks,
[&counter](int)
{
// Fire-and-forget inside a For loop inside a fire-and-forget!
vtkSMPTools::FireAndForget(
[&counter]()
{
// Final parallel work
vtkSMPTools::For(0, leafTasks,
[&counter](int)
{ counter.fetch_add(1, std::memory_order_relaxed); });
});
});
});
}
Fits nicely into the nested parallelism on/off. What do are your thought @jaswantp . Alternatively, one could just limit the number of threads and create a new C++ thread for handling async tasks. The thing is that we have a limited number of web-workers, so it would be more efficient to just extend the SMPTools
. Of course the real usage would be some task and when done, it would schedule an async call to be executed on the main application thread.