Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Define Thread Safe
Message
Information générale
Forum:
ASP.NET
Catégorie:
Autre
Divers
Thread ID:
01367996
Message ID:
01368207
Vues:
6
>>>What does 'Thread Safe' mean? Google search didn't turn up much in the way of explanations.
>>
>>It just basically means that the code will work in a multi-threaded environment and still function correctly. A lot of code isn't thread safe - imagine any code that sets a property through a method in an instance of a class. For example, if you had a loop which incremented a counter and the counter was a property. While that code is running another thread calls the same method and begins incrementing the same counter; it's pretty safe to assume your code will no longer behave correctly since you now have different threads messing with the same variable (property) at the same time. This code isn't threadsafe. Threadsafe code would ensure that multiple processes couldn't interact in bad ways (usually through some sort of locking, copying the property to a local var, etc.)
>
>This scenario sounds like there are multiple threads running inside the same app? I guess I always thought multi-threading meant running multiple threads outside of your app.

No, threads run inside the current app. Processes are outside of the app.

>1) Can you tell me under what kind of scenario you would use multiple threads in an app?

Two common places:

- You have a timer event which fires every minute or so and you do some processing. It's possible your processing is still occurring when the timer event fires again.
- You have a long running process but you don't want to lock up the user interface while it's occurring.

>2) What would make it thread safe?

That's a complicated question. It depends on the scenario and what your code is doing. Basically you eliminate side effects (changing anything outside of the scope of the current method), or you lock the resources you are planning on changing. You also tend to want to minimize the length of time locks are held, and avoid calling out to other methods (unless you're very careful and understand what types of things that other method might do); it's easy to introduce deadlocks when calling other code (you're holding locks the other code needs to also hold, so neither can continue).

For my example, you could do this:
public class SampleThread
{
   public int Counter { get; set; }
   public void IncrementCounter()
   {
      lock (this.Counter)
      {
         for(int i = 0; I < 10; i++)
         {
            this.Counter++;
            Console.WriteLine(this.Counter);
         }
      }      
   }
}
However, any code which requires access to the the.Counter property will be blocked until this code finishes.
-Paul

RCS Solutions, Inc.
Blog
Twitter
Précédent
Répondre
Fil
Voir

Click here to load this message in the networking platform