|
| 1 | +using UnityEngine; |
| 2 | +using System.Collections; |
| 3 | +using System.Threading; |
| 4 | + |
| 5 | +// Reference: http://www.dotnetperls.com/threadpool |
| 6 | +// Usage: Attach this script to gameobject in scene, press play, hit 1 key to queue new threads, see console for progress |
| 7 | + |
| 8 | +// we pass thread parameters as object |
| 9 | +class ThreadInfo |
| 10 | +{ |
| 11 | + public int threadIndex; |
| 12 | + public Vector3 myVector; |
| 13 | +} |
| 14 | + |
| 15 | + |
| 16 | +public class ThreadPoolTest : MonoBehaviour |
| 17 | +{ |
| 18 | + int maxThreads = 2; // set your max threads here |
| 19 | + |
| 20 | + static readonly object _countLock = new object(); |
| 21 | + static int _threadCount = 0; |
| 22 | + static bool closingApp = false; |
| 23 | + |
| 24 | + int clickCounter = 0; |
| 25 | + |
| 26 | + void Update() |
| 27 | + { |
| 28 | + // press 1 to spawn thread(s) |
| 29 | + if (Input.GetKeyDown(KeyCode.Alpha1)) |
| 30 | + { |
| 31 | + // Pass these values to the thread. |
| 32 | + ThreadInfo threadData = new ThreadInfo(); |
| 33 | + threadData.myVector = Random.insideUnitSphere * 10; // get some random vector3 value |
| 34 | + threadData.threadIndex = ++clickCounter; |
| 35 | + print("Queue new thread #"+ threadData.threadIndex); |
| 36 | + ThreadPool.QueueUserWorkItem(new WaitCallback(MyWorkerThread), threadData); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + private void MyWorkerThread(System.Object a) |
| 41 | + { |
| 42 | + // Constrain the number of worker threads, loop here until less than maxthreads are running |
| 43 | + while (!closingApp) |
| 44 | + { |
| 45 | + // Prevent other threads from changing this under us |
| 46 | + lock (_countLock) |
| 47 | + { |
| 48 | + if (_threadCount < maxThreads && !closingApp) |
| 49 | + { |
| 50 | + // Start processing |
| 51 | + _threadCount++; |
| 52 | + break; |
| 53 | + } |
| 54 | + } |
| 55 | + Thread.Sleep(50); |
| 56 | + } |
| 57 | + |
| 58 | + if (closingApp) return; |
| 59 | + |
| 60 | + // we are ready to work now, prepare object that contains necessary info for the thread |
| 61 | + ThreadInfo threadInfo = a as ThreadInfo; |
| 62 | + Vector3 myVector = threadInfo.myVector; |
| 63 | + int myIndex = threadInfo.threadIndex; |
| 64 | + print("---From thread #"+ myIndex + " processing myVector " + myVector); |
| 65 | + |
| 66 | + // for testing we just sleep here (you could do your heavy calculations here) |
| 67 | + Thread.Sleep(5000); |
| 68 | + |
| 69 | + // add this to your heavy work loop, so the thread quits if scene is closed |
| 70 | + //if (closingApp) return; |
| 71 | + |
| 72 | + print("---Finished thread #"+ myIndex); |
| 73 | + |
| 74 | + // decrease thread counter, so other threads can start |
| 75 | + _threadCount--; |
| 76 | + } |
| 77 | + |
| 78 | + // set bool to close threads on exit |
| 79 | + void OnDestroy() |
| 80 | + { |
| 81 | + closingApp = true; |
| 82 | + } |
| 83 | + |
| 84 | +} |
0 commit comments