Avatar of CyrexCore2k
CyrexCore2k
Flag for United States of America asked on

Problems with semaphores?

I've only recently started writing (functional) multi-threaded applications. I was just curious if, aside from being a bit cumbersome at times, there's any drawbacks to using semaphores for thread synchronization.
C#Java.NET Programming

Avatar of undefined
Last Comment
CyrexCore2k

8/22/2022 - Mon
PlatoConsultant

threads are unpredictable from execution point of view. Its not possible to say when thread will be active and how much work it will do. That is why when many threads access shared resources then it can cause unpredictable behavior of whole application and its results. That is why threads must be synchronized in such situations and this is done through semaphores and mutexes. But this not important for .NET programmers because this work is done behind the scene
PlatoConsultant

Design Ur Multi Threaded application Properly

When working with threads, then therere two application designs of thread usage:

·        Pipeline model

In this case threads work on different operations in different stages and those threads have a very little in common. Typical sample is a game where rendering operations are assigned to separated thread, next one deals with AI, another works on network communication etc.

·        Worker thread model

In this model application has threads that work on the same task in parallel manner. Typically this model is used by web servers (or servers in general) handling HTTP communication when worker threads are assigned to each HTTP session and other related operations. Because thread creation demands many system resources and time, this operation is cached in a format of thread pools where worker threads are pooled. For instance when request is sent to a server then available pooled thread is assigned to it. When pool is out of threads the new ones are created continually so server isnt overloaded and when server detects reducing load then destroys unused threads to minimum.

can u show ur working model
CyrexCore2k

ASKER
"That is why threads must be synchronized in such situations and this is done through semaphores and mutexes. But this not important for .NET programmers because this work is done behind the scene"

o_o Um, it definitely isn't. I was just wondering if there were any drawbacks between the various options available in .Net for protecting critical sections. Semaphores, Mutexes and lock statements are the only ones I know of. Are there any others? Are they all pretty much the same?
Your help has saved me hundreds of hours of internet surfing.
fblack61
PlatoConsultant

Most of the .net Classes are thread safe that is they are manage their synchronization them selves u dont have to handle ur self.


u dont have to worry about thread synchronization
PlatoConsultant

For Example
The SynchronizedCollection stores data in a List container and provides an object that can be set and used to synchronize access to the collection so that it is thread-safe. The IList container can be recovered using the Items method. The synchronized object can be recovered using the SyncRoot property. It can only be set using one of the constructors that take the syncRoot parameter.

Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe.
PlatoConsultant

Queues are also thread safe with some conditions

Queues are useful for storing messages in the order they were received for sequential processing. Objects stored in a Queue are inserted at one end and removed from the other.

Public static (Shared in Visual Basic) members of this type are thread safe. A Queue can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. To guarantee thread safety during enumeration, you can lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

using System;
using System.Collections.Generic;
 
class Example
{
    public static void Main()
    {
        Queue<string> numbers = new Queue<string>();
        numbers.Enqueue("one");
        numbers.Enqueue("two");
        numbers.Enqueue("three");
        numbers.Enqueue("four");
        numbers.Enqueue("five");
 
        // A queue can be enumerated without disturbing its contents.
        foreach( string number in numbers )
        {
            Console.WriteLine(number);
        }
 
        Console.WriteLine("\nDequeuing '{0}'", numbers.Dequeue());
        Console.WriteLine("Peek at next item to dequeue: {0}", 
            numbers.Peek());
        Console.WriteLine("Dequeuing '{0}'", numbers.Dequeue());
 
        // Create a copy of the queue, using the ToArray method and the
        // constructor that accepts an IEnumerable<T>.
        Queue<string> queueCopy = new Queue<string>(numbers.ToArray());
 
        Console.WriteLine("\nContents of the first copy:");
        foreach( string number in queueCopy )
        {
            Console.WriteLine(number);
        }
        
        // Create an array twice the size of the queue and copy the
        // elements of the queue, starting at the middle of the 
        // array. 
        string[] array2 = new string[numbers.Count * 2];
        numbers.CopyTo(array2, numbers.Count);
        
        // Create a second queue, using the constructor that accepts an
        // IEnumerable(Of T).
        Queue<string> queueCopy2 = new Queue<string>(array2);
 
        Console.WriteLine("\nContents of the second copy, with duplicates and nulls:");
        foreach( string number in queueCopy2 )
        {
            Console.WriteLine(number);
        }
 
        Console.WriteLine("\nqueueCopy.Contains(\"four\") = {0}", 
            queueCopy.Contains("four"));
 
        Console.WriteLine("\nqueueCopy.Clear()");
        queueCopy.Clear();
        Console.WriteLine("\nqueueCopy.Count = {0}", queueCopy.Count);
    }
}

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
PlatoConsultant

So As u r Designing ur Application Check for the Thread Safety in the dot Net documentation. Thanks a lot..


ASKER CERTIFIED SOLUTION
CyrexCore2k

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.