How to synchronize multiple threads?

In certain load tests you want to make sure a bunch of threads reach a particular state before they proceed with the rest of the work. You cannot make sure that all threads execute a point simultaneously since the CPU scheduling would determine this. However you can move these threads to Ready. A ready-thread is a thread can be scheduled for execution on a particular core – http://msdn.microsoft.com/en-us/library/dd627187%28VS.85%29.aspx

WaitForMultipleObjects helps synchronize multiple user mode threads.

“The WaitForMultipleObjects function determines whether the wait criteria have been met. If the criteria have not been met, the calling thread enters the wait state until the conditions of the wait criteria have been met or the time-out interval elapses.”

Here is a small example of how to start multiple threads and then let them proceed after all of them have reached a particular point in execution.

using System;using System.Threading;using System.IO;namespace TestThreading{    class Program    {        const int ThreadCount = 10;        static ManualResetEvent[] events = new ManualResetEvent[ThreadCount];        static ThreadStart onStart = new ThreadStart(Start);        static int locked = -1;        static void Main(string[] args)        {            Thread[] threads = new Thread[ThreadCount];            for (int i = 0; i < ThreadCount; i++)            {                threads[i] = new Thread(onStart);                events[i] = new ManualResetEvent(false);            }            for (int i = 0; i < ThreadCount; i++)            {                threads[i].Start();            }            Console.ReadLine();        }        private static void Start()        {            int threadCount = Interlocked.Increment(ref locked);            Console.WriteLine("Thread {0} started & waiting", threadCount);            Thread.Sleep(3000); //Simulate some work befor setting.            events[threadCount].Set();            ManualResetEvent.WaitAll(events);            Console.WriteLine("Thread {0} proceeded", threadCount);        }    }}