Sunday, 1 September 2013

Multithreading keywords in C#


What is threading and multithreading? Max thread in 32 bit OS is pow(2,10)-1 and 64 bit OS is pow(2,15)-1

Threading is a light weight process, its basic unit to which OS allocate processor time and also its path of execution which is running on CPU while Multithreading is use to run the different part of the program in the same program using multiple threads.

Advantage: Resource sharing and increase the overall performance of an application.
In real time: Monitor input from the user, perform background tasks, and handle simultaneous streams of input.                                                                         


Signature of the constructor of a thread class?   
Thread(Runnable threadob,String threadName)


What are all the four states associated in the thread?    
Ans : 1. new 2. runnable 3. blocked 4. dead


What are the two types of multitasking?           
1.process-based  
2.Thread-based


When two threads are waiting on each other and can't proceed the program is said to be in a deadlock?  
True


What is meant by time slicing or time sharing?  
Time slicing is the method of allocating CPU time to individual threads in a priority schedule.


What’s difference between thread and process?  
1.  A thread is a path of execution that run on CPU, a process is a collection of threads that share the same virtual memory 
      2. A thread is a limited degree of isolation while process is isolated in the system level
      3. Thread always run in a process context and A process has at least one thread of execution


What are the two most important way for thread uses 
1.     If you’ve created the thread yourself, call Join on the thread. 
2.     If you’re on a pooled thread, use an event wait handle.


Can we have multiple threads in one App domain? 
One or more threads run in an AppDomain. An AppDomain is a runtime representation of a logical process within a physical process.Each AppDomain is started with a single thread, but can create additional threads from any of its threads.


What are all the methods available in the Runnable Interface?
Ans : run()


What are the two ways to create the thread?  
1.by implementing Runnable                
2.by extending Thread


The run() method should necessary exists in clases created as subclass of thread?  
True


Difference between the sleep and yield() ?
1. Thread.Sleep(0) relinquishes the thread’s current time slice immediately, voluntarily handing over the CPU to other threads. Framework 4.0’s new Thread.Yield() method does the same thing—except that it relinquishes only to threads running on the same processor.
2. Sleep(0) or Yield is occasionally useful in production code for advanced performance tweaks. It’s also an excellent diagnostic tool for helping to uncover thread safety issues: if inserting Thread.Yield() anywhere in your code makes or breaks the program, you almost certainly have a bug.


Different types of thread ? 
 
1. Start: Used to start a thread 

2. Sleep: Sleep will immediately place a thread in a wait state if time is given 0.
Thread's execution can be paused by determining that how long the thread should sleep. Example Thread.CurrentThread.Sleep(2000). Unit will be in millisecond and log type 

3. Stop:  Used to stop a thread 

4. Abort : Thread.Abort() - stops the thread execution at that moment itself.  

5. Suspend : The thread does not suspend until the .NET runtime determines that it is in a safe place to suspend it. Suspend allows you to block a thread until another thread calls Thread.ResumeThe suspend()method is used to terminate a thread”? False
  
6. Resume: Immediately thread will reach to the Wait mode 

7. Join: Useful for determining if a thread has completed before starting another task
              Which method waits for the thread to die ? join() method 

8. Join(Int) : . If the thread ends before the time-out, Join returns True; otherwise it returns False. 

9. IsAlive: What is the data type for the method isAlive() and this method is available in which class? Ans : boolean, Thread 

10. Destroy:

11. Running: 

12. ThreadState:  property can be used to get detail of a thread

13. Thread.CurrentThread: Refers to the current thread running in the method.Thread.Sleep (System.Threading.Timeout.Infinite) - thread into the sleep state for an indeterminate amount of time by calling.To interrupt this 

sleep you can call the Thread.Interrupt method


What is daemon thread's  and how can a thread be created as Daemon? 
Daemon thread's run in background and stop automatically when nothing is running program.Example of a Daemon thread is "Garbage collector".Garbage collector runs until some .NET code is running or else its idle. You can make a thread Daemon by Thread.Isbackground=true 
Note:  We can use events with threads , this is one of the technique to synchronize one thread with other. 


Exception handling in threading concept 
In writing such exception handling blocks, rarely would you ignore the error: typically, you’d log the details of the exception, and then perhaps display a dialog allowing the user to automatically submit those details to your web server. You then might shut down the application—because it’s possible that the error corrupted the program’s state. However, the cost of doing so is that the user will lose his recent work—open documents, for instance.

The “global” exception handling events for WPF and Windows Forms applications (Application.DispatcherUnhandledException and Application.ThreadException) fire only for exceptions thrown on the main UI thread. You still must handle exceptions on worker threads manually.
AppDomain.CurrentDomain.UnhandledException fires on any unhandled exception, but provides no means of preventing the application from shutting down afterward.


What is the method available for setting the priority?  
Ans : setPriority()


Which priority Thread can prompt the lower primary Thread?                  
Higher Priority


What is the Thread Priority?   
A thread s Priority property determines how much execution time it gets relative to other active threads in the operating system, on the following scale: 
enum ThreadPriority{ Lowest, BelowNormal, Normal, AboveNormal, Highest }     

What are all the values for the following level (max-priority, min-priority, normal-priority)
10,1,5


What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?
1. wait(),notify() & notifyall()                 2. Object class


Which of the following is true?
1) wait(),notify(),notifyall() are defined as final & can be called only from with in a synchronized method
2) Among wait(),notify(),notifyall() the wait() method only throws IOException
3) wait(),notify(),notifyall() & sleep() are methods of object class
Ans : All are true


How can you avoid deadlock in threading ?  
1.     Monitor , Interlocked classes , Wait handles, Event raising from one thread to other thread , 
2.     ThreadState property which you can poll and act accordingly etc. 


What is difference between deadlock and race condition?
1.   Deadlock occurs when two threads lock each other’s resources while Race condition occurs when two threads "race" for access to a resource.
      2.   Deadlock, both threads are blocked and will never wake up while Race, when two or more threads are able to access shared data and they try to change it at the same time.
Note: Can avoid deadlock or race using "lock" an object so that only the thread that locked it can work with it.


What are the lock, monitor, mutex and semaphore? 
Lock : Once lock is acquired, completed  task then we do not know when lock will get released
Monitor: Monitor.Enter is acquire the lock and Monitor.Exit will release the lock if monitor.Enter is not define and trying to release the lock using Monitor.Exit then will throw an exception
Note: Both(Lock and Monitor) are running on the same domain.
Mutex: Only that thread will perform a task on the variable who has mutex ownership and other thread will be in waiting mode when other thread will claim for ownership then will acquiring the ownership only when first thread will release the ownership.
Note: Lock, Monitor and Mutex are used to avoid the race and deadlock condition.
In real time: Read Like Locking mechanism
Semaphore:Semaphore controls access to a shared pool of resources. It provides operations to Wait() until one of the resources in the pool becomes available, and Signal() when it is given back to the pool.
In real time: Used for synchronization problems like producer-consumer, traffic signal etc.


What is thread pooling? Explain advantage and disadvantage?
Thread pooling: used to manage different threads which are running for short period of time
Advantage: Cut these overheads by time sharing and recycling threads because thread creation take 100 ms and by default occupy 1 MB memory. and avoid the overhead of the switching thread in different context of the program
Disadvantage: If you are waiting on I/O, or waiting on an event, etc then you tie up that thread pool thread and it can't be used by anyone else. Same idea applies to long running tasks like download a data, perform a disk I/O operation etc.
In real time: Downloading stuff from remote servers like bit torrent
Note: ThreadPool is leveraging multi-core processors to execute computationally intensive code in parallel in “divide-and-conquer” style.


Which scenario is required to use thread pool?
Consider a process that has several components running. Each of those components could be creating worker threads. The more threads in your process, the more time is wasted on context switching. Now, if each of those components were queuing items to the thread pool, you would have a lot less context switching overhead. The thread pool is designed to maximize the work being done across your CPUs (or CPU cores). That is why, by default, the thread pool spins up multiple threads per processor.


There are a number of ways to enter the thread pool:
   1.      Via the Task Parallel Library (from Framework 4.0) 
   2.      By calling ThreadPool.QueueUserWorkItem
   3.      Via asynchronous delegates
   4.      Via BackgroundWorker


There are a few things to be varying of when using pooled threads: 
1. You cannot set the Name of a pooled thread, making debugging more difficult (although you can attach a description when debugging in Visual Studio’s Threads window).
2. Pooled threads are always background threads (this is usually not a problem). Blocking a pooled thread may trigger additional latency in the early life of an application unless you call ThreadPool.SetMinThread
3. You are free to change the priority of a pooled thread—it will be restored to normal when released back to the pool.
4. You can query if you’re currently executing on a pooled thread via the property Thread.CurrentThread.IsThreadPoolThread.


What is a Background Thread? What is a Foreground Thread? When do you do something in Background Thread vs do the same in Foreground Thread? 
Background Thread: Background threads are threads which will get terminated when all foreground threads are closed. The application won't wait for them to be completed and having Thread.isbackground = true
Foreground Thread: Foreground threads are threads which will continue to run until the last foreground thread is terminated.
In real time: In Microsoft word, background thread may be used for spelling check and foreground thread is used to check the input which has stroke by keyword


What is Volatile? 
Volatile keyword indicates that a field might be modified by multiple threads that are executing at the same time. Fields that are declared volatile are not subject to compiler optimizations that assume access by a single thread. This ensures that the most up-to-date value is present in the field at all times. The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access.

Advantage: Doesn’t force synchronization of loads and stores, by eliminating reordering optimizations, action take place when the bool flag is true.

Disadvantage: In some cases, can volatile fields cause a performance problem if they are used too much so it’s better idea not to use volatile in your programs at all. However, if you are using a volatile field that is accessed in a tight loop millions of times, you can copy it into a regular local variable and then use that local variable. This will provide a performance boost.

In real time: Use volatile in multithreaded programs and with flag variables

No comments:

Post a Comment