Thread synchronization

In my work experience, associates always felt that multithreaded applications provide the illusion that numerous activities are happening at more or less the same time.  Interestingly, on observing CPU/system reality, it is considered as Time Slice to switch between different threads. It is based on round-robin methodology.

Process-based multitasking handles the concurrent execution of programs, while thread-based multitasking deals with the concurrent execution of pieces of the same program.

In this section, it is essential to highlight the risk factor of thread collision during a multithreading process in an enterprise application.  On building any multithreaded application, shared data should be protected from the possibility of multiple thread engagement with its content/value.

Let's illustrate with a simple example:

    static void Main(string[] args)
{
Console.WriteLine("Demo of Thread Synchronize");
Console.WriteLine("##########################");
Console.WriteLine("Main Thread starts here...");
WorkerThreadClass p = new WorkerThreadClass();

/* Group of 7 threads creation
* for synchronize execution
*/
Thread[] threadList = new Thread[7];
for (int i = 0; i < 7; i++)
{
threadList[i] = new Thread(new
ThreadStart(p.SyncThreadProcess));
}
foreach (Thread thread in threadList)
{
thread.Start();
}
Console.WriteLine("Main Thread ends here...");
Console.ReadLine();
}

Now, the key factor is to protect the shared block using the lock option. It requires us to specify a token to acquire by a thread to enter within the lock scope:

    class WorkerThreadClass
{
// Synchronization Lock object
private Object ThreadLock = new object();
public void SyncThreadProcess()
{
//Lock to synchronize
lock (ThreadLock)
{
Console.WriteLine("Starting Thread with ID: {0}",
Thread.CurrentThread.ManagedThreadId);
Console.WriteLine("Lock the operation of Thread");
for (int i = 1; i <= 10; i++)
{
Console.Write(i + " ");
}
Console.WriteLine("n Release the Lock to
other Thread");
}
}
}

On attempting to lock down an instance-level method, the execution can simply pass the reference to that instance. Once the thread enters into a lock scope, the lock token (in our example, the  ThreadLock object) is inaccessible by other threads until the lock is released or the lock scope has exited.

The execution result depicts the process in a clear way, as shown here:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.157.34