I’ve implemented a small framework for multi-threading applications in a very clear way. It’s called “Executors Framework” and is inspired by similar constructs that are available in the Java standard library.
Comments and feedback very welcome! Especially if you spot bugs or potential threading unsafeties. When it appears solid enough, I will link to the page from the Scripts list.
I couldn’t find anything like this in the .NET libraries, which is why I implemented it. Feel free to mention if this already exists in .NET, and I will put on the fool hat.
<:)
Edit: I should mention that this is for advanced users only - do not attempt to introduce multi-threading in your regular Unity code. The primary uses for this framework is when you are doing heavy isolated computations, or are interfacing with external entities/libs that have blocking calls or long return times.
Cool stuff! I’m not very familiar with C#'s threading libraries, so I can’t tell you if there’s something similar in there. All I know is that I really like this way of working in Java, and am happy to see it usable withing Unity.
Begin/EndInvoke does not let you specify the manner in which the task gets processed. For me it’s very nice to be able to change between threaded and non-threaded by just changing a single instantiation line.
Yes, but it sort of defeats the purpose of the whole framework… because the callback would be called from a foreign thread, which is the “can of worms” we’re trying to avoid.
can of worms is a nice word for it
Unity isn’t threadsafe, on a real multi threading system chances are pretty realistic that it will bomb …
you can already see errors happening due to parallel www request to the same domain actually as the data loading for the data in the WWW object is async in unity 2.6.x too
I just got a nice idea for this - by introducing a Unity component class called ExecutionManager, we can do the polling in there and support the callback pattern that you requested. Will update the code soon.
Actually… that code won’t work in Unity (even 3.0) I think, because it uses .NET 3.5 classes. And I did try good old delegates, but ran into synchronization problems. It appears to not be thread-safe to use surrounding-scope variables in a delegate called by another thread:
for(int i = 1; i < 10; i++) {
futures.Add(executor.Submit<double>(delegate () { return i*i; } ));
expectedAnswers.Add(i * i);
}
Or could this be just a Unity/Mono bug in this regard? I kind of expected ints like these to be copied into some kind of anonymous invisible object for the delegate to refer to, which should be thread safe.