Upload
weetoz
View
23
Download
3
Embed Size (px)
DESCRIPTION
Multithreading
Citation preview
877.791.9571 |
C# Multithreading Example
2
TweetTweet
17
Introduction
The term “multithread programming” may sound complicated, but it is quite easy to doin C#.net. This article explains how multithreading works on your typical, general-purpose computer. You will learn how the operating system manages thread executionand how to manipulate the Thread class in your program to create and start managed
Download &
ResourcesSign up for our newsletter toget the latest updates.
SUBMITSUBMIT
View our FREE mini-
courses!
SIGN UP NOW SIGN UP NOW
Discounted
Boot
Camps
SIGN UP NOWSIGN UP NOW
5
ShareShare
HomeHome ContributorsContributors ArticlesArticles Mini CoursesMini Courses DownloadsDownloads CoursesCourses ScheduleSchedule
AboutAbout
threads. This article also renders the information you need to know whenprogramming application with multiple threads such as Thread class, pools, threadingissues and backgroundWorker.
Multithreading Overview
A thread is an independent stream of instructions in a program. Each written programis a paradigm of sequential programming in which they have a beginning, an end, asequence, and a single point of execution. A thread is similar to sequential program.However, a thread itself is not a program, it can’t run on its own, but runs within aprogram.
The real concern surrounding threads is not about a single sequential thread, butrather the use of multiple threads in a single program all running at the same timeand performing different tasks. This mechanism referred as Multithreading. A thread isconsidered to be a lightweight process because it runs within the context of a programand takes advantage of resources allocated for that program.
Threads are important both for client and server applications. While in C# programcoding, when you type something in editor, the dynamic help (intellisense) Windowsimmediately shows the relevant topics that fit to the code. One thread is waiting forinput from the user, while other does some background processing. A third thread canstore the written data in a temporary file, while another one downloads a file from aspecific location.
With the task manager, you can turn on the Thread column and see the processes andthe number of threads for every process. Here, you can notice that only cmd.exe isrunning inside a single thread while all other applications use multiple threads.
The operating system schedules threads. A thread has priority and every thread has itsown stack, but the memory for the program code and heap are shared among allthreads of a single process.
A process consists of one or more threads of execution which is simply referred asthreads. A process always consists of at least one thread called as Main thread (Main()method). A single thread process contains only one thread while multithread processcan contains more than one thread of execution.
On a computer, the operating system loads and starts applications. Each application orservice runs as a separate process on the machine. The following image illustrates thatthere are quite few processes actually running than there are applications. Many of theprocesses are background operating system processes that are started automaticallywhen the computer powers up.
System.Threading Namespace
Under .NET platform, the System.Threading namespace provides a number of typesthat enable the direct construction of multithreaded application.
Type Description
Thread It represents a thread that execute within the CLR. Usingthis, we can produce additional threads in applicationdomain.
Mutex It is used for synchronization between application domains.
Monitor It implements synchronization of objects using Locks andWait.
Smaphore It allows limiting the number of threads that can access aresource concurrently.
Interlock It provides atomic operations for variables that are sharedby multiple threads.
ThreadPool It allows you to interact with the CLR maintained threadpool.
ThreadPriority This represents the priority level such as High, Normal, Low.
System.Threading.Thread class
The Thread class allows you to create and manage the execution of managed threadsin your program. They are called managed threads because you can directlymanipulate each thread you create. You will found the Thread class along with useful
stuffs in the System.Threading namespace.
Member Type Description
CurrentThread Static Return a reference of current runningthread.
Sleep Static Suspend the current thread for a specificduration.
GetDoamin Static Return a reference of current applicationdomain.
CurrentContext Static Return a reference of current context inwhich the thread currently running.
Priority Instance level Get or Set the Thread priority level.
IsAlive Instance level Get the thread state in form of True or Falsevalue.
Start Instance level Instruct the CLR to start the thread.
Suspend Instance level Suspend the thread.
Resume Instance level Resume a previously suspended thread.
Abort Instance level Instruct the CLR to terminate the thread.
Name Instance level Allows establishing a name to thread.
IsBackground Instance level Indicate whether a thread is running inbackground or not.
Multithreading Implementation
The following section plays with the numerous System.Threading namespace staticand instance-level members and properties.
Obtaining Current Thread Information’s
To illustrate the basic use of Thread type, suppose you have console application inwhich CurrentThread property retrieves a Thread object that represents the currentlyexecuting thread.
123456789101112131415161718192021
using System;using System.Threading; namespace threading{ class Program { static void Main(string[] args) { Console.WriteLine("**********Current Thread Informations***************n" Thread t = Thread.CurrentThread; t.Name = "Primary_Thread"; Console.WriteLine("Thread Name: {0}", t.Name); Console.WriteLine("Thread Status: {0}", t.IsAlive); Console.WriteLine("Priority: {0}", t.Priority); Console.WriteLine("Context ID: {0}", Thread.CurrentContext.ContextID); Console.WriteLine("Current application domain: {0}" Console.ReadKey(); }
After compiling this application, the output would be as following;
Simple Thread Creation
The following simple example explains the Thread class implementation in which theconstructor of Thread class accepts a delegate parameter. After the Thread class objectis created, you can start the thread with the Start() method as following;
After running the application, you got the following output of the two threads as:
The important point to be noted here is that, there is no guarantee what output comefirst meaning, which thread start first. Threads are scheduled by the operating system.So which thread comes first can be different each time.
Background Thread
The process of the application keeps running as long as at least one foreground threadis running. If more than one foreground thread is running and the Main() method ends,
222324
}}
12345678910111213141516171819202122
using System;using System.Threading; namespace threading{ class Program { static void Main(string[] args) { Thread t = new Thread(myFun); t.Start(); Console.WriteLine("Main thread Running"); Console.ReadKey(); } static void myFun() { Console.WriteLine("Running other Thread"); } }}
the process of the application keeps active until all foreground threads finish theirwork.
When you create a thread with the Thread class, you can define if it should be aforeground or background thread by setting the property IsBackground. The Main()method set this property of the thread t to false. After setting the new thread, the mainthread just writes to the console an end message. The new thread writes a start and anend message, and in between it sleep for two seconds.
When you compile this application, you will still see the completion message writtento the console because the new thread is a foreground thread. Here, the output asfollowing;
If you change the IsBackground property to start the new thread to true, the resultshown at the console is different as follows:
Concurrency issues
Programming with multiple threads is not an easy task. When starting multiple threadsthat access the same data, you can get intermediate problems that are hard to resolve.When you build multithreaded applications, you program needs to ensure that any
12345678910111213141516171819202122232425
using System;using System.Threading; namespace threading{ class Program { static void Main(string[] args) { Thread t = new Thread(myFun); t.Name = "Thread1"; t.IsBackground = false; t.Start(); Console.WriteLine("Main thread Running"); Console.ReadKey(); } static void myFun() { Console.WriteLine("Thread {0} started", Thread.CurrentThread.Name); Thread.Sleep(2000); Console.WriteLine("Thread {0} completed", Thread.CurrentThread.Name); } }}
piece of shared data is protected against the possibility of numerous threads changingits value.
Race Condition
A race condition can occurs if two or more threads access the same objects and accessto the shared state is not synchronized. To illustrate the problem of Race condition,let’s build a console application. This application uses the Test class to print 10numbers by pause the current thread for a random number of times.
After compiling this program, the primary thread within this application domain beginsby producing five secondary threads. Each working threads told to call the Calculatemethod on the same Test class instance. So you have taken none of precaution to lockdown this object’s shared resources. Hence, all of five threads start to access theCalculation method simultaneously. This is the Race Condition and the applicationproduce unpredictable output as following;
123456789101112131415161718192021222324252627282930313233343536373839
Using System;using System.Threading; namespace threading{ public class Test { public void Calculation() { for (int i = 0; i < 10; i++) { Thread.Sleep(new Random().Next(5)); Console.Write(" {0},", i); } Console.WriteLine(); } } class Program { static void Main(string[] args) { Test t = new Test(); Thread[] tr = new Thread[5]; for (int i = 0; i < 5; i++) { tr[i] = new Thread(new ThreadStart(t.Calculation)); tr[i].Name = String.Format("Working Thread: {0}" } //Start each thread foreach (Thread x in tr) { x.Start(); } Console.ReadKey(); } }}
Deadlocks
Having too much locking into an application can get your application into trouble. In adeadlock, at least two threads wait for each other to release a lock. As both threadswait for each other, a deadlock situation occurs and thread wait endlessly and yourcomputer eventually hanged.
Here, the both of methods changed the state of the two objects obj1 and obj2 bylocking them. The methods DeadLock1() first lock obj1 and next for obj2. The methodDeadLock2() first lock obj2 and then obj1.So lock for obj1 is resolved next threadswitch occurs and second method start to run and gets the lock for obj2. The secondthread now waits for the lock of obj1. Both of threads now wait and don’t release eachother. This is typically deadlock.
Want to learn more?? The InfoSec Institute AdvancedComputer Forensics Training trains you on critical forensicskills that are difficult to master outside of a lab enviornment.Already know how to acquire forensically sound images?Perform file carving? Take your existing forensic knowledgefurther and sharpen your skills with this Advanced ComputerForensics Boot Camp from InfoSec Institute. Upon thecompletion of our Advanced Computer Forensics Boot Camp,students will know how to:
Perform Volume Shadow Copy (VSC) analysisAdvanced level file and data structure analysis for XP,Windows 7 and Server 2008/2012 systemsTimeline Analysis & Windows Application AnalysisiPhone Forensics
VIEW ADV FORENSICS
12345678910111213
using System;using System.Threading; namespace threading{ class Program { static object obj1 = new object(); static object obj2 = new object(); public static void DeadLock1() { lock (obj1)
Synchronization
Problems that can happen with multiple threads such as Race condition and deadlockscan be avoided by Synchronization. It is always suggested to avoid concurrency
Want to learn more?? The InfoSec Institute AdvancedComputer Forensics Training trains you on critical forensicskills that are difficult to master outside of a lab enviornment.Already know how to acquire forensically sound images?Perform file carving? Take your existing forensic knowledgefurther and sharpen your skills with this Advanced ComputerForensics Boot Camp from InfoSec Institute. Upon thecompletion of our Advanced Computer Forensics Boot Camp,students will know how to:
Perform Volume Shadow Copy (VSC) analysisAdvanced level file and data structure analysis for XP,Windows 7 and Server 2008/2012 systemsTimeline Analysis & Windows Application AnalysisiPhone Forensics
141516171819202122232425262728293031323334353637383940414243444546474849
{ Console.WriteLine("Thread 1 got locked"); Thread.Sleep(500); lock (obj2) { Console.WriteLine("Thread 2 got locked"); } } } public static void DeadLock2() { lock (obj2) { Console.WriteLine("Thread 2 got locked"); Thread.Sleep(500); lock (obj1) { Console.WriteLine("Thread 1 got locked"); } } } static void Main(string[] args) { Thread t1 = new Thread(new ThreadStart(DeadLock1)); Thread t2 = new Thread(new ThreadStart(DeadLock2)); t1.Start(); t2.Start(); Console.ReadKey(); } }}
VIEW ADV FORENSICS
issues by not sharing data between threads. Of course, this is not always possible. Ifdata sharing is necessary, you must use synchronization so that only one thread at atime accesses and changes shared states. This section discusses varioussynchronization technologies.
Locks
We can synchronize access of shared resources using the lock keyword. By doing so,
incoming threads cannot interrupt the current thread, preventing it from finishing itswork. The lock keyword required an object reference.
By taking the previous Race Condition problem, we can refine this program byimplementing lock on crucial statements to make it foolproof from race conditions asfollowing;
After compiling this program, this time it produced the desired result as follows. Here,each thread has sufficed opportunity to finish its tasks.
Monitor
The lock statement is resolved by the compiler to the use of the Monitor class. TheMonitor class is almost similar to locks but has a big advantage compared to the lockstatements in terms of control. You are able to instruct the active thread to wait forsome duration time and inform waiting threads when the current thread is completed.Once processed by C# compiler, a lock scope resolves to the following code.
12345678910111213141516171819
public class Test { public object tLock = new object(); public void Calculation() { lock (tLock) { Console.Write(" {0} is Executing",Thread.CurrentThread.Name); for (int i = 0; i < 10; i++) { Thread.Sleep(new Random().Next(5)); Console.Write(" {0},", i); } Console.WriteLine(); } } }
If you see the IL code of the Lock application using ILDASM, you will found the Monitorclass reference over there as follows:
Using [Synchronization] Attribute
The [Synchronization] attribute is a member of System.Runtime.Remoting.Contextnamespace. This class level attribute effectively locks down all instance of the objectfor thread safety
Mutex
Mutex stand for Mutual Exclusion is method that offers synchronization across multiple
12345678910111213141516171819
object tLock = new object();public void Calculation(){ Monitor.Enter(tLock); try { for (int i = 0; i < 10; i++) { Thread.Sleep(new Random().Next(5)); Console.Write(" {0},", i); } } catch{} finally { Monitor.Exit(tLock); } Console.WriteLine();}
12345678910111213141516171819
object tLock = new object();public void Calculation(){ Monitor.Enter(tLock); try { for (int i = 0; i < 10; i++) { Thread.Sleep(new Random().Next(5)); Console.Write(" {0},", i); } } catch{} finally { Monitor.Exit(tLock); } Console.WriteLine();}
threads. The Mutex calss derive from WaitHandle, you can do a WaitOne() to acquirethe mutex lock and be the owner of the mutex that time. The mutex is released byinvoking the ReleaseMutex() method as following;
Once you successfully compile this program, it shows up that each newly created firstentered into its application domain. Once, it finished its tasks then it released andsecond thread started and so on.
Semaphore
12345678910111213141516171819202122232425262728293031323334353637383940
using System;using System.Threading; namespace threading{ class Program { private static Mutex mutex = new Mutex(); static void Main(string[] args) { for (int i = 0; i < 4; i++) { Thread t = new Thread(new ThreadStart(MutexDemo)); t.Name = string.Format("Thread {0} :", i+1); t.Start(); } Console.ReadKey(); } static void MutexDemo() { try { mutex.WaitOne(); // Wait until it is safe to enter. Console.WriteLine("{0} has entered in the Domain" Thread.CurrentThread.Name); Thread.Sleep(1000); // Wait until it is safe to enter. Console.WriteLine("{0} is leaving the Domainrn" Thread.CurrentThread.Name); } finally { mutex.ReleaseMutex(); } } }}
A semaphore is very similar to Mutex but semaphore can be used by multiple threadsat once while Mutex can’t. With a Semaphore, you can define a count how manythreads are allowed to access the resources shielded by semaphore simultaneously.
Here in the following example, five threads are created and two semaphore. In theconstructor of semaphore class, you can define no of locks that can be acquired with asemaphore.
While we run this application, two semaphores are immediately created and rest ofwait because we have create five thread. So three are in waiting state. The movement,any one of thread released the rest of created one by one as following.
123456789101112131415161718192021222324252627282930313233343536373839
using System;using System.Threading; namespace threading{ class Program { static Semaphore obj = new Semaphore(2, 4); static void Main(string[] args) { for (int i = 1; i <= 5; i++) { new Thread(SempStart).Start(i); } Console.ReadKey(); } static void SempStart(object id) { Console.WriteLine(id + "-‐-‐>>Wants to Get Enter"); try { obj.WaitOne(); Console.WriteLine(" Success: " + id + " is in!" Thread.Sleep(2000); Console.WriteLine(id + "<<-‐-‐ is Evacuating"); } finally { obj.Release(); } } }}
By Ajay Yadav | June 21st, 2013 | Forensics | 5 Comments
Share This Story, Choose Your Platform!
About the Author: Ajay Yadav
Summary
This article explained how to code applications that utilize multiple threads using theSystem.Threading Namespace. Using multithreading in your application can causeconcurrency issues such as Race condition and deadlocks. Finally, this article discussesthe various ways of synchronization such as Locks, Mutex, and Semaphore to handleconcurrency problems in which you can protect thread sensitive block of code toensure that shared resources do not become unusual.
Ajay Yadav is an author, Cyber Security Specialist, SME, SoftwareEngineer, and System Programmer with more than eight years of workexperience. He earned a Master and Bachelor Degree in ComputerScience, along with abundant premier professional certifications. For
several years, he has been researching Reverse Engineering, Secure Source Coding,Advance Software Debugging, Vulnerability Assessment, System Programming andExploit Development. He is a regular contributor to programming journal andassistance developer community with blogs, research articles, tutorials, trainingmaterial and books on sophisticated technology. His spare time activity includestourism, movies and meditation. He can be reached at om.ajay007[at]gmail[dot]com
5 Comments
Leave A Comment
b3h3m0th June 26, 2013 at 6:09 am - Reply
I have just one question. Why C#?
ajay July 1, 2013 at 8:07 pm - Reply
Because .NET leverages with amazing tools and we can manipulatemultithreading in better ways rather than c or c++ except Java Framework.
Mahek Sabharwal October 9, 2013 at 9:51 am - Reply
When I originally commented I clicked the “Notify me when newcomments are added” checkbox and
now each time a comment is added I get four emails with the same comment.Is there any way you can remove me from that service?Thanks!
Deependra December 14, 2013 at 8:30 am - Reply
Hi Ajay,I think you have missed example for Using [Synchronization] Attribute.
Jesse Roper May 19, 2014 at 11:50 pm - Reply
Great article. Was helpful. Deependra is right – you’re missing the examplecode for the [Synchronization] attribute, but here’s an example that I have
tested and confirmed:[Synchronization()]public class SampleSynchronized : ContextBoundObject {// A method that does some work, and returns the square of the given number.public int Square(int i) {Console.Write(“The hash of the thread executing “);Console.WriteLine(“SampleSynchronized.Square is: {0}”,Thread.CurrentThread.GetHashCode());return i*i;}
ARCHIVESARCHIVES
Select Month
POPULAR SEARCHPOPULAR SEARCH
TERMSTERMS
agile android
applicationsecurity App Security
bootcamp certifications CISA
CISM CISSP compliance
crackme ethical hackingexploit development
feature featured
forensicsgeneralsecurityhacking how-to human
resources infosecdocs
interview iphone ITAuditing java linux
malware malware analysismanagement management
RECENT POSTSRECENT POSTS
Simple yet Effective Methodsto Solve Java Security Issues
Aggressive Chinese IPHighlights Attribution Issues
Android Application hackingwith Insecure Bank Part 1
Foreign Hackers ConstantlyTarget US CriticalInfrastructure
Penetration TestingMethodology for WebApplications
The Windows KerberosVulnerability: What You Needto Know
The dos and don’ts of sharingsensitive business data
How to Enjoy a HackerConference and an InfoSecGathering
Maximizing SSH SecurityService in the Cloud
Understanding DiskEncryption on Android andiOS
SEARCH THIS SITESEARCH THIS SITE
Search ...
LIKE US ON FACEBOOKLIKE US ON FACEBOOK
== STAY UP TO DATE== STAY UP TO DATE
InfoSec Institute12 217LikerLiker
Name (required) Email (required) Website
Comment...
POST COMMENTPOST COMMENT
7 − three =
compliance and auditing nmap
penetration testing
reverseengineeringreversing scada securitysecurity awareness social
media sql injection TOR
training vulnerabilitiesvulnerability wapt
wordpress
Copyright © 2012 - InfoSec Institute | All Rights Reserved !"#$