views:

61

answers:

1

Hi,

I've got this code below, where I spawn several threads, normally about 7, and join them to wait until all are done:

            List<Thread> threads = new List<Thread>();
            Thread thread;
            foreach (int size in _parameterCombinations.Keys)
            {
                thread = new Thread(new ParameterizedThreadStart(CalculateResults));
                thread.Start(size);
                threads.Add(thread);
            }

            // wait for all threads to finish
            for (int index = 0; index < threads.Count; index++)
            {
                threads[index].Join();
            }

When I check this most of the time only one or two threads are running at the same time, only once or twice when I rerun the app all of them executed.

Is there any way to force all the threads to start executing?

Many thanks.

A: 

Your code is fine.. i changed it abit to show you that the execution of the thread is not limited to 2 threads. I would look for problems in the calculation process..

class Program
{
    static void Main(string[] args)
    {
        List<Thread> threads = new List<Thread>();
        Thread thread;
        for (int i = 0; i < 7; i++)
        {
            thread = new Thread(new ParameterizedThreadStart(CalculateResults));
            thread.Start();
            threads.Add(thread);
        }

        // wait for all threads to finish
        for (int index = 0; index < threads.Count; index++)
        {
            threads[index].Join();
        }
    }

    static void CalculateResults(object obj)
    {
        Console.WriteLine("Thread number " + Thread.CurrentThread.ManagedThreadId + " is alive");
        Thread.Sleep(1000);
        Console.WriteLine("Thread number " + Thread.CurrentThread.ManagedThreadId + " is closing");
    }
}
Adibe7
Adibe, thanks for pointing me in the right direction. I replaced the call to my CPU intensive function with Thread.Sleep and it worked fine. The Calculate function consumes all of CPU and its difficult for the OS to switch threads I suspect.
@misha-r: Your calculation threads will be preempted and rescheduled by the OS as needed.
Brian Rasmussen