*
Previous WPF-Question-Answers-71-80 WPF-Question-Answers-1-10 Next

Dot net Framework (C#) Threading Question Answers - 41-50

41. What is Mutex?

A Mutex (short for Mutual Exclusion) is a synchronization primitive used to ensure that only one thread or process can access a shared resource at a time.

๐Ÿ” Key Concepts

  • Exclusive Access: When a thread acquires a mutex, other threads or processes trying to acquire it are blocked until it's released.
  • Cross-Process Support: Unlike lock or Monitor in C#, which work only within a single process, a Mutex can synchronize access across multiple processes.
  • Critical Section Protection: Mutex is ideal for protecting code that accesses shared resources like files, databases, or memory.

๐Ÿงช Example in C#

using System;
using System.Threading;

class Program {
    static Mutex mutex = new Mutex();

    static void Main() {
        for (int i = 0; i < 3; i++) {
            Thread t = new Thread(AccessResource);
            t.Name = $"Thread-{i + 1}";
            t.Start();
        }
    }

    static void AccessResource() {
        Console.WriteLine($"{Thread.CurrentThread.Name} is requesting the mutex");
        mutex.WaitOne(); // Acquire the mutex
        Console.WriteLine($"{Thread.CurrentThread.Name} has entered the protected area");
        Thread.Sleep(500); // Simulate work
        Console.WriteLine($"{Thread.CurrentThread.Name} is leaving the protected area");
        mutex.ReleaseMutex(); // Release the mutex
    }
}

โš ๏ธ Important Notes

  • A thread must release the mutex it acquires; otherwise, it can cause deadlocks.
  • Mutex is heavier than lock or Monitor due to its ability to work across processes.

42. What is ParameterizedThreadStart()?

Similar to ThreadStart, but takes one object parameter.

static void Main()
{
  Thread t = new Thread(Print);
  t.Start("Hello from t!");
}
static void Print(object messageObj)
{
  string message = (string) messageObj;
  Console.WriteLine(message);
}

43. What is QueueUserWorkItem?

QueueUserWorkItem is a static method, belongs to System.Threading Namespace. Used to Queue a method in the thread pool for execution. Uses WaitCallback Delegate which returns void and takes one parameter of type Object. Returns bool type result. It returns 'true' if the method is successfully queued otherwise throws an exception 'NotSupportedException.

static void Main()
{
  ThreadPool.QueueUserWorkItem(DoWork);
  ThreadPool.QueueUserWorkItem(DoWork, 56);
  Console.ReadLine();
}
static void DoWork(object data)
{
  Console.WriteLine("Hi from the thread pool! " + data);
}
// Output:
// Hi from the thread pool!
// Hi from the thread pool! 56

44. What is Race Condition?

A race condition happens when threads concurrently access and modify shared resources, and results depend on unpredictable execution order.

45. What is ReaderWriterLock?

Allows multiple readers or a single writer at a time. Reader and writer requests are queued separately. Writers wait until all readers release locks.

ReaderWriterLock is used to synchronize access to a resource. At any given time, it allows either concurrent read access for multiple threads, or write access for a single thread.

A thread can hold a reader lock or a writer lock, but not both at the same time.

Readers and writers are queued separately. When a thread releases the writer lock, all threads waiting in the reader queue at that instant are granted reader locks; when all of those reader locks have been released, the next thread waiting in the writer queue, if any, is granted the writer lock,

46. What is Semaphore?

A Semaphore limits the number of threads that can access a resource simultaneously.

47. What is Single-Threaded Apartment (STA)?

Single-threaded apartments contains only one thread. All objects in this apartment can receive method calls from only this thread. Objects does not need synchronization because all methods calls are comes synchronously from single thread.

Single-threaded apartment needs a message queue to handle calls from other threads. When other threads calls an object in STA thread then the method call are queued in the message queue and STA object will receive a call from that message queue.

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.

48. What is synchronization?

Synchronization coordinates threads to produce predictable outcomes, preventing conflicts when accessing shared resources.

49. What is System.Threading.SpinWait?

SpinWait is a lightweight synchronization tool that loops for a given count, used internally by Monitor and ReaderWriterLock. SpinWait is a lightweight synchronization type. The SpinWait method is useful for implementing locks. Monitor and ReaderWriterLock, use this method internally. SpinWait essentially puts the processor into a very tight loop, with the loop count specified by the iterations parameter. The duration of the wait therefore depends on the speed of the processor.

SpinWait is designed to be used in conjunction with the .NET Framework types that wrap kernel events such as ManualResetEvent. SpinWait can also be used by itself for basic spinning functionality in just one program.

50. What is the thread state when created?

Unstarted state.

Back to Index
Previous WPF-Question-Answers-71-80 WPF-Question-Answers-1-10 Next
*
*