Thread Pools (basics)

When you deal with many threads you should consider thread pools. Creating threads costs some time and resources. And even worse, you cannot reuse a thread.

Thread pool threads stay alive. The purpose is to use them again. They are waiting in a queue to be assigned new jobs. You do not have to instantiate a new thread each time you have a new job. Overall it reduces the number of threads. And in fact it does not help you a lot to have 100 threads running on a four processor machine. The system might even slow down, because it performs a lot of context switching.

Thread pools can automatically manage the amount of threads.

static void hello(object o) {
  for (int i = 0; i < 1000; i++) {
    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " line " + i + " " + o as string);
    Thread.Sleep(2);    // let's wait 2 milliseconds to get some interaction between the two threads
  }
} //

static void Main(string[] args) {
  ThreadPool.QueueUserWorkItem(hello, "SomeFunnyParameter");
  ThreadPool.QueueUserWorkItem(hello);
  Console.ReadLine();
} //

 

Advertisements

About Bastian M.K. Ohta

Happiness only real when shared.

Posted on December 3, 2013, in Basic, C#, Threading and tagged , , , . Bookmark the permalink. 1 Comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: