-
Notifications
You must be signed in to change notification settings - Fork 1
/
ThreadTaskPool.cs
50 lines (43 loc) · 1.1 KB
/
ThreadTaskPool.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* * * * * * * * * * * * * * * * * * * * * *
* Simple Multithreading in Unity
* callym 2015
* * * * * * * * * * * * * * * * * * * * * *
* Makes sure that you never run too many tasks
*
* TODO:
* * optimise...
* * * * * * * * * * * * * * * * * * * * * */
using UnityEngine;
using System.Threading;
using System.Collections.Generic;
static public class ThreadTaskPool
{
static Queue<ThreadTask> tasks = new Queue<ThreadTask>();
static List<ThreadTask> runningTasks = new List<ThreadTask>();
static int numRunningTasks = 0;
static int maxRunningTasks = SystemInfo.processorCount - 1; // want to leave the main thread...
static public void FinishTask(ThreadTask t)
{
numRunningTasks--;
runningTasks.Remove(t);
RunTask();
}
static public void QueueTask(ThreadTask t)
{
tasks.Enqueue(t);
RunTask();
}
static public void RunTask()
{
if (numRunningTasks < maxRunningTasks && tasks.Count > 0)
{
ThreadTask t = tasks.Dequeue();
ThreadPool.QueueUserWorkItem(
new WaitCallback(delegate(object ob)
{
t.RunTask();
}), null);
t.StartCoroutine(t.WaitForCallback());
}
}
}