.net

Multi-threading

1)What is Multi-tasking ?
Its a feature of modern operating systems with which we can run multiple programs at same time example Word,Excel etc.

(2)What is Multi-threading ?
Multi-threading forms subset of Multi-tasking instead of having to switch between programs this feature switches between different parts of the same program.Example you are writing in word and at the same time word is doing a spell check in background.

(3)What is a Thread ?
A thread is the basic unit to which the operating system allocates processor time.

(4)Did VB6 support multi-threading ?
While VB6 supports multiple single-threaded apartments, it does not support a free-threading model, which allows multiple threads to run against the same set of data.

(5)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. Note :- All threading classes are defined in System.Threading namespace.

(6)Which namespace has threading ?
Systems.Threading has all the classes related to implement threading.Any .NET application who wants to implement threading has to import this namespace. Note :- .NET program always has atleast two threads running one the main program and second the garbage collector.

(7)How can we change priority and what the levels of priority are provided by .NET ?
Thread Priority can be changed by using Threadname.Priority = ThreadPriority.Highest.In the sample provided look out for code where the second thread is ran with a high priority.
Following are different levels of Priority provided by .NET :-
v ThreadPriority.Highest
v ThreadPriority.AboveNormal
v ThreadPriority.Normal
v ThreadPriority.BelowNormal
v ThreadPriority.Lowest

(8)What does Addressof operator do in background ?
The AddressOf operator creates a delegate object to the BackgroundProcess method. A delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread has been instantiated, you begin the execution of the code by calling the Start() method of the thread

(9)How can you reference current thread of the method ?
“Thread.CurrentThread” refers to the current thread running in the method.”CurrentThread” is a public static property.

(10) What’s Thread.Sleep() in threading ?
Thread’s execution can be paused by calling the Thread.Sleep method. This method takes an integer value that determines how long the thread should sleep. Example Thread.CurrentThread.Sleep(2000).

(11)How can we make a thread sleep for infinite period ?
You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread.Sleep (System.Threading.Timeout.Infinite).To interrupt this sleep you can call the Thread.Interrupt method.

(12) What is Suspend and Resume in Threading ?
It is Similar to Sleep and Interrupt. Suspend allows you to block a thread until another thread calls Thread.Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until the .NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state. Note :- In threading interviews most people get confused with Sleep and Suspend.They look very similar.

(13)What the way to stop a long running thread ?
Thread.Abort() stops the thread execution at that moment itself.

(14)What’s Thread.Join() in threading ?
There are two versions of Thread.Join :-
v Thread.join().
v Thread.join(Integer) this returns a boolean value.
The Thread.Join method is useful for determining if a thread has completed before starting another task. The Join method waits a specified amount of time for a thread to end. If the thread ends before the time-out, Join returns True; otherwise it returns False.Once you call Join the calling procedure stops and waits for the thread to signal that it is done. Example you have “Thread1” and “Thread2″ and while executing ‘Thread1” you call “Thread2.Join()”.So “Thread1” will wait until “Thread2” has completed its execution and the again invoke “Thread1”. Thread.Join(Integer) ensures that threads do not wait for a long time.If it exceeds a specific time which is provided in integer the waiting thread will start.

(15)What are 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

(16) When working with shared data in threading how do you implement synchronization ?
There are a somethings you need to be careful with when using threads. If two threads (e.g. the main and any worker threads) try to access the same variable at the same time, you’ll have a problem. This can be very difficult to debug because they may not always do it at exactly the same time. To avoid the problem, you can lock a variable before accessing it. However, if two threads lock the same variable at the same time, you’ll have a deadlock problem. SyncLock x ‘Do something with x End SyncLock

(17)Can we use events with threading ?
Yes you can use events with threads , this is one of the technique to synchronize one thread with other.

(18)How can we know a state of a thread?
“ThreadState” property can be used to get detail of a thread.Thread can have one or combination of status.System.Threading.Threadstate enumeration has all the values to detect a state of thread.Some sample states are Isrunning,IsAlive,suspended etc.

(19) What is use of Interlocked class ?
Interlocked class provides methods by which you can achieve following functionalities :-
v increment Values.
v Decrement values.
v Exchange values between variables.
v Compare values from any thread. in a synchronization mode.
Example :- System.Threading.Interlocked.Increment(IntA)

(20) what is a monitor object?
Monitor objects are used to ensure that a block of code runs without being interrupted by code running on other threads. In other words, code in other threads cannot run until code in the synchronized code block has finished. SyncLock and End SyncLock statements are provided in order to simplify access to monitor object.

(21) what are wait handles ?
Twist :- What is a mutex object ? Wait handles sends signals of a thread status from one thread to other thread.There are three kind of wait modes :-
v WaitOne.
v WaitAny.
v WaitAll.
When a thread wants to release a Wait handle it can call Set method.You can use Mutex (mutually exclusive) objects to avail for the following modes.Mutex objects are synchronization objects that can only be owned by a single thread at a time.Threads request ownership of the mutex object when they require exclusive access to a resource. Because only one thread can own a mutex object at any time, other threads must wait for ownership of a mutex object before using the resource. The WaitOne method causes a calling thread to wait for ownership of a mutex object. If a thread terminates normally while owning a mutex object, the state of the mutex object is set to signaled and the next waiting thread gets ownership

(22) what is ManualResetEvent and AutoResetEvent ?
Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling the Set method. There are two synchronization event classes. Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of ManualResetEvent instances to nonsignaled using the Reset method or when control returns to a waiting WaitOne call. Instances of the AutoResetEvent class can also be set to signaled using Set, but they automatically return to nonsignaled as soon as a waiting thread is notified that the event became signaled.

(23) What is ReaderWriter Locks ?
You may want to lock a resource only when data is being written and permit multiple clients to simultaneously read data when data is not being updated. The ReaderWriterLock class enforces exclusive access to a resource while a thread is modifying the resource, but it allows nonexclusive access when reading the resource. ReaderWriter locks are a useful alternative to exclusive locks that cause other threads to wait, even when those threads do not need to update data.
(24) How can you avoid deadlock in threading ?
A good and careful planning can avoid deadlocks.There so many ways microsoft has provided by which you can reduce deadlocks example Monitor ,Interlocked classes , Wait handles, Event raising from one thread to other thread , ThreadState property which you can poll and act accordingly etc.
(25) What’s difference between thread and process?
A thread is a path of execution that run on CPU, a process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always run in a process context. Note:- Its difficult to cover threading interview question in this small chapter.These questions can take only to a basic level.If you are attending interviews where people are looking for threading specialist , try to get more deep in to synchronization issues as that’s the important point they will stress.

*********************************************************************************************************

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

2)What is the signature of the constructor of a thread class?
Thread(Runnable threadob,String threadName)

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

4)What are all the methods available in the Thread class?
1.isAlive()
2.join()
3.resume()
4.suspend()
5.stop()
6.start()
7.sleep()
8.destroy()

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

6)What is the mechanisam defind by java for the Resources to be used by only one Thread at a time?
Ans : Synchronisation

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

8)How many threads at a time can access a monitor?
one

9)Which method waits for the thread to die ?
join() method

10)What is meant by daemon thread? In java runtime, what is it’s role?
Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java runtime system

*********************************************************************************************************

1) What are the two types of multitasking?

Ans :

1.process-based

2.Thread-based

2) What are the two ways to create the thread?

Ans :

1.by implementing Runnable

2.by extending Thread

3) What is the signature of the constructor of a thread class?

Ans : Thread(Runnable threadob,String threadName)

4) What are all the methods available in the Runnable Interface?

Ans : run()

5) What is the data type for the method isAlive() and this method is available in which class?

Ans : boolean, Thread

6) What are all the methods available in the Thread class?

Ans :

1.isAlive()

2.join()

3.resume()

4.suspend()

5.stop()

6.start()

7.sleep()

8.destroy()

7) What are all the methods used for Inter Thread communication and what is the class in which these methods are defined?

Ans :

1. wait(),notify() & notifyall()

2. Object class

8) What is the mechanism defined by java for the Resources to be used by only one Thread at a time?

Ans : Synchronization

9) What is the procedure to own the moniter by many threads?

Ans : not possible

10) What is the unit for 1000 in the below statement?

ob.sleep(1000)

Ans : long milliseconds

11) What is the data type for the parameter of the sleep() method?

Ans : long

12) What are all the values for the following level?

max-priority

min-priority

normal-priority

Ans : 10,1,5

13) What is the method available for setting the priority?

Ans : setPriority()

14) What is the default thread at the time of starting the program?

Ans : main thread

15) The word synchronized can be used with only a method.

True/ False

Ans : False

16) Which priority Thread can prompt the lower primary Thread?

Ans : Higher Priority

17) How many threads at a time can access a monitor?

Ans : one

18) What are all the four states associated in the thread?

Ans : 1. new 2. runnable 3. blocked 4. dead

19) The suspend()method is used to terminate a thread?

True /False

Ans : False

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

True /False

Ans : True

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

True/False

Ans : True

22) Which method waits for the thread to die ?

Ans : join() method

23) 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

1. 1
2. 2
3. 3
4. 1 & 2
5. 1,2 & 3

Ans : D

24) Garbage collector thread belongs to which priority?

Ans : low-priority

25) What is meant by time slicing or time sharing?

Ans : Time slicing is the method of allocating CPU time to individual threads in a priority schedule.

26) What is meant by daemon thread? In java run time, what is it’s role?

Ans : Daemon thread is a low priority thread which runs intermittently in the background doing the garbage collection operation for the java run time system.

*****************************************************************************************************

Process and Threads
A process is a collection of virtual memory space, code, data, and system resources. A thread is code that is to be serially executed within a process.

Process always has at least one thread of execution, known as the primary thread. A process can have multiple threads in addition to the primary thread.

Threads vs. Processes
Both threads and processes and they are time sliced with other threads and processes. The key differences are

1. All threads within a single application are logically contained within a process.
2. Processes are fully isolated from each other but threads share the heap memory with other threads running in the same process\application.

Foreground and Background Threads
1. Foreground threads keep the application alive. But background threads do not keep the application alive on their own. They terminate immediately once all foreground threads have ended.
2. By default threads are foreground threads. Thread can be set as background thread. (thread.IsBackground = true; )

Deadlock Condition
A deadlock occurs when each thread is waiting for the other to do something A race condition occurs when one thread finishes before another on which it depends, causing the former to use a bogus value because the latter has not yet supplied a valid one.

Race Condition
A race condition exists when a thread modifies a resource to an invalid state, and then another thread attempts to access that resource and use it in the invalid state

Synchronizing objects
Lock
Locks are useful when only one thread at a time can be allowed to modify data or some other controlled resource.

Monitors
Monitors are Like the lock keyword, monitors prevent blocks of code from simultaneous execution by multiple threads. The Enter method allows one and only one thread to proceed into the following statements; all other threads are blocked until the executing thread calls Exit. This is just like using the lock keyword. In fact, the lock keyword is implemented with the Monitor class.

Mutex
A mutex is similar to a monitor; it prevents the simultaneous execution of a block of code by more than one thread at a time. In fact, the name “mutex” is a shortened form of the term “mutually exclusive.” Unlike monitors, however, a mutex can be used to synchronize threads across processes.

Semaphore is same as Mutex but it ensures not more than a specified number of threads can access a resource, or section of code.

Double-check locking for Signleton classes.

More at Multithreaded Singleton: Double-check locking

public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();

    public static Singleton Instance {
get {
if (instance == null) {
lock (syncRoot) {
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}

Apartments
COM objects in the process as divided into groups called apartments. A COM object lives in exactly one apartment, in the sense that its methods can legally be directly called only by a thread that belongs to that apartment. Any other thread that wants to call the object must go through a proxy.

There are two types of apartments: single-threaded apartments, and multithreaded apartments.

1.Single-threaded Apartments—Single-threaded apartments consist of exactly one thread, so all COM objects that live in a single-threaded apartment can receive method calls only from the one thread that belongs to that apartment. All method calls to a COM object in a single-threaded apartment are synchronized with the windows message queue for the single-threaded apartment’s thread. A process with a single thread of execution is simply a special case of this model.

2. Multithreaded Apartments—Multithreaded apartments consist of one or more threads, so all COM objects that live in an multithreaded apartment can receive method calls directly from any of the threads that belong to the multithreaded apartment. Threads in a multithreaded apartment use a model called free-threading. Calls to COM objects in a multithreaded apartment are synchronized by the objects themselves.

Leave a comment