Thread variable question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Extremest

    Thread variable question

    I am new to threading and trying to figure some things out. Are all
    variables in a thread set to only that thread? Meaning if I create 2
    instances of a class and then put each one in a different thread and
    run them will the local variables in functions be shared or will they
    be thread safe?

  • Andy Bates

    #2
    Re: Thread variable question

    Each thread will have it's own stack and set of registers. The other
    components are down to how you write your code. A penalty occurs when a
    thread context switches but that is a different story.

    If you create two threads with instances of class X then they each will own
    totally separate instances of X. All calls will operate as in a single
    threaded application provided that they are not sharing resources! The code
    of X may be shared but the data will be totally separate.

    If X has a constructor that takes an object Y and for each of the classes
    above you provide the same Y object then this becomes a shared resource
    (shared resources can be databases, files, handles, registry anything where
    a potential collision could occur (i.e. two threads trying to write to the
    same stream isn't a good idea)).

    Say that Y is a counter for the number of times something happens (an
    instance of where you would want a single instance shared). In this scenario
    Y is a shared object and just doing count++ is a property or method is not
    going to cut it.

    You get nasty things like race conditions where both threads try and update
    the count at exactly the same time. It may not happen very often but you can
    lose data, get random crashes and unpredictable behaviour.

    What we need to do is either make Y thread safe or serialise access to the
    shared components.

    In our example in class Y with the counter property we can either:

    1. lock the object. This is a Monitor or Critical section and will prevent
    any other threads in whilst a thread owns it. If another thread comes along
    while a thread is owning the lock then it will block (wait until it becomes
    free) otherwise it will claim the lock and execute the code (hence only one
    thread can be executing the code within the lock statement).

    public void IncrementCounte r()
    {
    lock(y) { this.counter++; }
    }

    2. The Interlocked class provides some atomic functions for manipulating
    simple scalar types (Int32, Int64) etc. The operations take exactly one
    clock tick so there is no chance of two threads getting part way through an
    operation (i.e. as in load value, increment, store value; it's just
    increment value).

    public void IncrementCounte r()
    {
    Interlocked.Inc rement(this.cou nter);
    }

    There are also lots of classes to control synchronisation (Monitor, Events,
    Semaphore, Mutexes) but hopefully the above will get you started.

    With different shared resources you get different problems. In memory
    objects are fairly easy to serialise but SQL database access need careful
    consideration as the database is also obviously multi-user so you shouldn't
    need to serialise your code to access it, but depending on what calls you
    make you can get into deadlock situations where two threads (or even
    different processes on different computers) are going after the same locks
    on a shared resource (being a SQL database table).

    HTH

    - Andy

    "Extremest" <dnncampbell1@c harter.netwrote in message
    news:1157087228 .781371.209360@ i3g2000cwc.goog legroups.com...
    >I am new to threading and trying to figure some things out. Are all
    variables in a thread set to only that thread? Meaning if I create 2
    instances of a class and then put each one in a different thread and
    run them will the local variables in functions be shared or will they
    be thread safe?
    >

    Comment

    • admin@binindex.net

      #3
      Re: Thread variable question

      ok this is my main. What do I have wrong with it?

      class Program
      {
      static string[] categories = { "emulation" , "audio" ,
      "console" , "anime" , "xxx" , "tv" , "pictures" , "video" };


      static void Main(string[] args)
      {
      string proc = Process.GetCurr entProcess().Pr ocessName;
      // get the list of all processes by that name
      Process[] processes = Process.GetProc essesByName(pro c);
      // if there is more than one process...
      if (processes.Leng th 1)
      {
      //MessageBox.Show ("Applicatio n is already running");
      return;
      }
      else
      {
      for (int x = 0; x < categories.Leng th; x++)
      {
      MasterList master = new MasterList();
      Groups groups = new Groups(categori es[x]);
      WorkerClass WC1 = new WorkerClass(mas ter, groups);
      WorkerClass WC2 = new WorkerClass(mas ter, groups);
      WorkerClass WC3 = new WorkerClass(mas ter, groups);
      WorkerClass WC4 = new WorkerClass(mas ter, groups);
      Thread Worker1 = new Thread(new
      ThreadStart(WC1 .Start));
      Thread Worker2 = new Thread(new
      ThreadStart(WC2 .Start));
      Thread Worker3 = new Thread(new
      ThreadStart(WC3 .Start));
      Thread Worker4 = new Thread(new
      ThreadStart(WC4 .Start));
      Worker1.Name = "Worker1";
      Worker2.Name = "Worker2";
      Worker3.Name = "Worker3";
      Worker4.Name = "Worker4";
      Worker1.Start() ;
      Worker2.Start() ;
      Worker3.Start() ;
      Worker4.Start() ;
      Worker4.Join();
      Worker3.Join();
      Worker2.Join();
      Worker1.Join();
      Console.WriteLi ne(master.size( ));
      master.SetEnume rator();
      Updater U1 = new Updater(master, categories[x]);
      Updater U2 = new Updater(master, categories[x]);
      Updater U3 = new Updater(master, categories[x]);
      Thread Updater1 = new Thread(new
      ThreadStart(U1. insert));
      Thread Updater2 = new Thread(new
      ThreadStart(U2. insert));
      Thread Updater3 = new Thread(new
      ThreadStart(U3. insert));
      Updater1.Start( );
      Updater2.Start( );
      Updater3.Start( );
      Updater1.Join() ;
      Updater2.Join() ;
      Updater3.Join() ;
      }
      }
      }
      }

      Comment

      • Peter Duniho

        #4
        Re: Thread variable question

        <admin@binindex .netwrote in message
        news:1159332235 .094870.278960@ d34g2000cwd.goo glegroups.com.. .
        ok this is my main. What do I have wrong with it?
        Why do you think there's something wrong with it?

        A suggestion: if you are specific with your question, you are much more
        likely to get help. Posting some random chunk of code and asking "what's
        wrong with it" is way too vague to be worth the time for anyone to bother
        with.


        Comment

        • admin@binindex.net

          #5
          Re: Thread variable question

          ok to be more clear the threads don't die is what I guess I want to
          say. The connections are all still open till the program stops
          running. I figured since the threadstate is stopped that it would then
          cleanup the thread, but I guess I am wrong about that.

          Comment

          • Brian Gideon

            #6
            Re: Thread variable question


            admin@binindex. net wrote:
            ok to be more clear the threads don't die is what I guess I want to
            say. The connections are all still open till the program stops
            running. I figured since the threadstate is stopped that it would then
            cleanup the thread, but I guess I am wrong about that.
            What connections? Can you post the code for your Start and insert
            methods?

            Brian

            Comment

            • admin@binindex.net

              #7
              Re: Thread variable question

              ok Sorry I figured it out. Forgot to actually close the connections
              that were staying open. Have that all fixed now.

              Comment

              Working...