Skip to content

Instantly share code, notes, and snippets.

@nobnak
Last active April 14, 2018 15:03
Show Gist options
  • Save nobnak/16d6e754bf85e42f45c8 to your computer and use it in GitHub Desktop.
Save nobnak/16d6e754bf85e42f45c8 to your computer and use it in GitHub Desktop.
Parallel.For for Unity
using System.Collections.Generic;
using System.Threading;
namespace Gist {
public static class Parallel {
static AutoResetEvent[] _resets;
public static void For(int fromInclusive, int toExclusive, System.Action<int> body) {
var numThreads = 2 * System.Environment.ProcessorCount;
if (_resets == null || _resets.Length != numThreads) {
_resets = new AutoResetEvent[numThreads];
for (var i = 0; i < numThreads; i++)
_resets [i] = new AutoResetEvent (false);
}
var work = new WaitCallback ((i) => {
var ii = (int)i;
var j = ii + fromInclusive;
for (var k = (int)j; k < toExclusive; k += numThreads)
body ((int)k);
_resets [ii].Set ();
});
lock (_resets) {
for (var i = 0; i < numThreads; i++)
ThreadPool.QueueUserWorkItem (work, i);
for (var i = 0; i < numThreads; i++)
_resets [i].WaitOne ();
}
}
public static void SerialFor(int fromInclusive, int toExclusive, System.Action<int> body) {
for (var i = fromInclusive; i < toExclusive; i++)
body (i);
}
}
}
@joergzdarsky
Copy link

Would you mind providing an example how you'd use your Parallel implementation in case you want to replace you sequential-for which could be for example:
for (int i = 0; i < gameObjects.Length; i++)
{
gameObjects[i].transform.localPosition += Physics.referenceFrameVelocity * Time.deltaTime;
}

Thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment