public static void ForGPU(int fromInclusive, int toExclusive, GPUTaskIterator<int> iterator, int perDevice = 1, List<int> deviceList = null) { int[] Items = new int[toExclusive - fromInclusive]; for (int i = 0; i < Items.Length; i++) Items[i] = i + fromInclusive; ForEachGPU(Items, iterator, perDevice, deviceList); }
public static void ForEachGPU <T>(IEnumerable <T> items, GPUTaskIterator <T> iterator, int perDevice = 1, List <int> deviceList = null) { int NDevices = GPU.GetDeviceCount(); if (deviceList == null) { deviceList = Helper.ArrayOfSequence(0, Math.Min(NDevices, items.Count()), 1).ToList(); } Queue <DeviceToken> Devices = new Queue <DeviceToken>(); for (int i = 0; i < perDevice; i++) { for (int d = deviceList.Count - 1; d >= 0; d--) { Devices.Enqueue(new DeviceToken(deviceList[d])); } } int NTokens = Devices.Count; foreach (var item in items) { while (Devices.Count <= 0) { Thread.Sleep(5); } DeviceToken CurrentDevice; lock (Devices) CurrentDevice = Devices.Dequeue(); Thread DeviceThread = new Thread(() => { GPU.SetDevice(CurrentDevice.ID % NDevices); iterator(item, CurrentDevice.ID); lock (Devices) Devices.Enqueue(CurrentDevice); }) { Name = $"ForEachGPU Device {CurrentDevice.ID}" }; DeviceThread.Start(); } while (Devices.Count != NTokens) { Thread.Sleep(5); } }