2019-07-22 22:17:46 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Concurrent;
|
|
|
|
|
using System.Collections.Generic;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
|
|
|
|
|
namespace Wabbajack.Common
|
|
|
|
|
{
|
|
|
|
|
public class WorkQueue
|
|
|
|
|
{
|
2019-08-29 22:49:48 +00:00
|
|
|
|
internal static BlockingCollection<Action> Queue = new BlockingCollection<Action>(new ConcurrentStack<Action>());
|
2019-07-22 22:17:46 +00:00
|
|
|
|
|
|
|
|
|
[ThreadStatic]
|
|
|
|
|
private static int CpuId;
|
|
|
|
|
|
2019-08-10 15:21:50 +00:00
|
|
|
|
[ThreadStatic]
|
|
|
|
|
internal static bool WorkerThread;
|
|
|
|
|
|
2019-08-02 23:04:04 +00:00
|
|
|
|
public static void Init(Action<int, string, int> report_function, Action<int, int> report_queue_size)
|
2019-07-22 22:17:46 +00:00
|
|
|
|
{
|
|
|
|
|
ReportFunction = report_function;
|
2019-08-02 23:04:04 +00:00
|
|
|
|
ReportQueueSize = report_queue_size;
|
2019-07-22 22:17:46 +00:00
|
|
|
|
ThreadCount = Environment.ProcessorCount;
|
|
|
|
|
StartThreads();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static void StartThreads()
|
|
|
|
|
{
|
|
|
|
|
Threads = Enumerable.Range(0, ThreadCount)
|
|
|
|
|
.Select(idx =>
|
|
|
|
|
{
|
|
|
|
|
var thread = new Thread(() => ThreadBody(idx));
|
|
|
|
|
thread.Priority = ThreadPriority.BelowNormal;
|
|
|
|
|
thread.IsBackground = true;
|
|
|
|
|
thread.Name = String.Format("Wabbajack_Worker_{0}", idx);
|
|
|
|
|
thread.Start();
|
|
|
|
|
return thread;
|
|
|
|
|
}).ToList();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static void ThreadBody(int idx)
|
|
|
|
|
{
|
|
|
|
|
CpuId = idx;
|
2019-08-10 15:21:50 +00:00
|
|
|
|
WorkerThread = true;
|
2019-07-22 22:17:46 +00:00
|
|
|
|
|
|
|
|
|
while(true)
|
|
|
|
|
{
|
|
|
|
|
Report("Waiting", 0);
|
|
|
|
|
var f = Queue.Take();
|
|
|
|
|
f();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
public static void Report(string msg, int progress)
|
|
|
|
|
{
|
|
|
|
|
ReportFunction(CpuId, msg, progress);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static void QueueTask(Action a)
|
|
|
|
|
{
|
|
|
|
|
Queue.Add(a);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public static Action<int, string, int> ReportFunction { get; private set; }
|
2019-08-02 23:04:04 +00:00
|
|
|
|
public static Action<int, int> ReportQueueSize { get; private set; }
|
2019-07-22 22:17:46 +00:00
|
|
|
|
public static int ThreadCount { get; private set; }
|
|
|
|
|
public static List<Thread> Threads { get; private set; }
|
2019-08-02 23:04:04 +00:00
|
|
|
|
public static int MaxQueueSize;
|
|
|
|
|
public static int CurrentQueueSize;
|
|
|
|
|
|
|
|
|
|
internal static void ReportNow()
|
|
|
|
|
{
|
|
|
|
|
ReportQueueSize(MaxQueueSize, CurrentQueueSize);
|
|
|
|
|
}
|
2019-07-22 22:17:46 +00:00
|
|
|
|
}
|
|
|
|
|
}
|