Skip to content

Instantly share code, notes, and snippets.

@quangnle
Created March 9, 2016 03:44
Show Gist options
  • Save quangnle/f32c7efcd9fb1057677b to your computer and use it in GitHub Desktop.
Save quangnle/f32c7efcd9fb1057677b to your computer and use it in GitHub Desktop.
my tiny threadpool
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadPool
{
class Program
{
static int MaxThreads = 10; // maximum thread to run at one time
static int _numOfThreads = 50; // amount of threads to be executed
static volatile int _curThreads = 0; // current running threads
static Queue<Thread> _handlers = new Queue<Thread>(); // threadpool
static readonly object _countLock = new object();
static void Main(string[] args)
{
for (int i = 0; i < _numOfThreads; i++)
{
Thread worker = new Thread(Run);
worker.Name = i.ToString();
_handlers.Enqueue(worker);
}
do
{
lock (_countLock)
{
if (_curThreads < MaxThreads && _handlers.Count > 0)
{
var t = _handlers.Dequeue();
t.Start();
}
Thread.Sleep(1000); // each thread starts after other 1 second
}
}
while (_curThreads > 0) ;
Console.Read();
}
public static void Run()
{
_curThreads++;
var threadNo = Thread.CurrentThread.Name;
Console.WriteLine("Thread {0} starts", threadNo);
for (int i = 0; i < 30; i++)
{
Thread.Sleep(400);
Console.WriteLine("Thread {0}: {1}", threadNo, i);
}
_curThreads--;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment