You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Zero/ZeroLevel/Services/Utils/Multiprocessor.cs

67 lines
1.9 KiB

5 years ago
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
namespace ZeroLevel.Utils
{
public class Multiprocessor<T>
: IDisposable
{
private BlockingCollection<T> _queue = new BlockingCollection<T>();
private List<Thread> _threads = new List<Thread>();
5 years ago
private bool _is_disposed = false;
5 years ago
5 years ago
public Multiprocessor(Action<T> handler, int size, int stackSize = 1024 * 1024)
5 years ago
{
for (int i = 0; i < size; i++)
{
var t = new Thread(() =>
{
try
{
T item;
5 years ago
while (!_is_disposed && !_queue.IsCompleted)
5 years ago
{
5 years ago
if (_queue.TryTake(out item, 500))
5 years ago
{
handler(item);
}
}
}
5 years ago
catch (Exception ex)
{
Log.Error(ex, "[Multiprocessor.HandleThread]");
}
5 years ago
}, stackSize);
t.IsBackground = true;
_threads.Add(t);
}
foreach (var t in _threads) t.Start();
}
public void Append(T t) => _queue.Add(t);
public void WaitForEmpty()
{
while (_queue.Count > 0)
{
Thread.Sleep(100);
}
}
public void Dispose()
{
_queue.CompleteAdding();
while (_queue.Count > 0)
{
Thread.Sleep(100);
}
5 years ago
_is_disposed = true;
Thread.Sleep(1000); // wait while threads exit
foreach (var thread in _threads) thread.Join();
5 years ago
_queue.Dispose();
}
}
}

Powered by TurnKey Linux.