Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop without blocking console output

I have been working on some multithreaded console applications recently and was wondering how to do this. I use this code to control the amount of threads created by the application:

foreach(string s in File.ReadAllLines("file.txt")){
    while (threads >= maxThreads) ;
    Thread t = new Thread(() => { 
        threads++;
        //thread code - make network request using 's'
        Console.WriteLine("TEST");
        threads--;
        Thread.CurrentThread.Abort();
    });
    t.start();
}

However, due to the while loop, the Console.WriteLine method in the created is blocked and does not show up until the next free thread is available.

Is there any way I can prevent this while loop from blocking the Console.WriteLine call?

EDIT - Reversed condition in while loop.

like image 902
rodit Avatar asked Apr 27 '15 21:04

rodit


2 Answers

UPDATE

Based on your comments...

The line

while (threads >= maxThreads) ;

is not a good way to await a change in thread state, because it will cause the CPU to spin in the while statement. Instead, use one of the mechanisms intended for thread synchronization, such as a Semaphore.

Here's an example of a SemaphoreSlim used for a very similar situation.

class TheClub      // No door lists!
{
  static SemaphoreSlim _sem = new SemaphoreSlim (3);    // Capacity of 3

  static void Main()
  {
    for (int i = 1; i <= 5; i++) new Thread (Enter).Start (i);
  }

  static void Enter (object id)
  {
    Console.WriteLine (id + " wants to enter");
    _sem.Wait();
    Console.WriteLine (id + " is in!");           // Only three threads
    Thread.Sleep (1000 * (int) id);               // can be here at
    Console.WriteLine (id + " is leaving");       // a time.
    _sem.Release();
  }
}
like image 105
Eric J. Avatar answered Oct 19 '22 23:10

Eric J.


Using the while loop and thread.abort (or thread.suspned) etc are CPU intensive and is not the right way for thread synchronization. Explore Manual and AutoResetEvents. They are very effective when it comes to thread synchronization and does not spike your CPU.

like image 38
XtremeBytes Avatar answered Oct 20 '22 01:10

XtremeBytes