Wait for synchronized access

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

    #1

    Wait for synchronized access

    Lets say I have a method UpdateCache() called from a single thread. I also
    have a method GetCache() called from multiple threads. When UpdateCache() is
    called, the cache updating is being processed. This can take time.

    In the mean time, some of the multiple threads have called GetCache(), but
    because the cache is being updated, I want them to wait for the
    UpdateCache() to finish.

    Something like this, in a very simplified code:

    public void UpdateCache()
    {
    updating = true;
    try { this.data = GetData(); }
    finally { updating = false; }
    }

    public MyCache GetCache()
    {
    while( updating )
    Thread.Sleep( 200 );
    return this.data;
    }

    If I use lock for obtaining the same functionality, I guess it will be
    something like this for the UpdateCache() method:

    public void UpdateCache()
    {
    lock(this)
    {
    this.data = GetData();
    }
    }

    But how can I rewrite this method ??

    public MyCache GetCache()
    {
    ?????
    return this.data;
    }

    I've seen some examples using Monitor.Enter, Monitor.Wait, Monitor.Pulse and
    Monitor.Exit on some lockable object before entering a synchronized section
    of a code... but is there some solution where multiple thread only waits,
    instead of locking an object ??

    Maybe there are some better ways to solve this ??


    Best of regards...


  • Nicholas Paldino [.NET/C# MVP]

    #2
    Re: Wait for synchronized access

    Roger,

    It's very simple. If you are sure that GetCache and UpdateCache will be
    called on separate threads, then you can do this:

    public MyCache GetCache()
    {
    // Lock on the same object that updatecache is processing.
    lock (this)
    // Return the data.
    return this.data;
    }

    public void UpdateCache()
    {
    // Lock on this while updating the data.
    lock (this)
    // Update the data.
    this.data = GetData();
    }

    By using the same object in the lock statement, only one thread at a
    time can access that section of code. So, when UpdateCache is called, if
    GetCache is called as well, then it will wait until that section of code
    locked by "this" is exited. Also, if GetCache is called, UpdateCache will
    not be called until that section in GetCache is exited.

    Hope this helps.


    --
    - Nicholas Paldino [.NET/C# MVP]
    - nicholas.paldin o@exisconsultin g.com

    "Roger Down" <roger.down@c2i .net> wrote in message
    news:umUV3e4eDH A.2236@TK2MSFTN GP12.phx.gbl...[color=blue]
    > Lets say I have a method UpdateCache() called from a single thread. I also
    > have a method GetCache() called from multiple threads. When UpdateCache()[/color]
    is[color=blue]
    > called, the cache updating is being processed. This can take time.
    >
    > In the mean time, some of the multiple threads have called GetCache(), but
    > because the cache is being updated, I want them to wait for the
    > UpdateCache() to finish.
    >
    > Something like this, in a very simplified code:
    >
    > public void UpdateCache()
    > {
    > updating = true;
    > try { this.data = GetData(); }
    > finally { updating = false; }
    > }
    >
    > public MyCache GetCache()
    > {
    > while( updating )
    > Thread.Sleep( 200 );
    > return this.data;
    > }
    >
    > If I use lock for obtaining the same functionality, I guess it will be
    > something like this for the UpdateCache() method:
    >
    > public void UpdateCache()
    > {
    > lock(this)
    > {
    > this.data = GetData();
    > }
    > }
    >
    > But how can I rewrite this method ??
    >
    > public MyCache GetCache()
    > {
    > ?????
    > return this.data;
    > }
    >
    > I've seen some examples using Monitor.Enter, Monitor.Wait, Monitor.Pulse[/color]
    and[color=blue]
    > Monitor.Exit on some lockable object before entering a synchronized[/color]
    section[color=blue]
    > of a code... but is there some solution where multiple thread only waits,
    > instead of locking an object ??
    >
    > Maybe there are some better ways to solve this ??
    >
    >
    > Best of regards...
    >
    >[/color]


    Comment

    • Jon Skeet

      #3
      Re: Wait for synchronized access

      Roger Down <roger.down@c2i .net> wrote:[color=blue]
      > Lets say I have a method UpdateCache() called from a single thread. I also
      > have a method GetCache() called from multiple threads. When UpdateCache() is
      > called, the cache updating is being processed. This can take time.
      >
      > In the mean time, some of the multiple threads have called GetCache(), but
      > because the cache is being updated, I want them to wait for the
      > UpdateCache() to finish.
      >
      > Something like this, in a very simplified code:[/color]

      <snip>

      The first thing to note with your design is that if GetCache is called
      and then used while you're later updating it, you might have problems.

      Aside from that, I believe ReaderWriterLoc k is what you're after - have
      a look for it in MSDN.

      --
      Jon Skeet - <skeet@pobox.co m>
      Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

      If replying to the group, please do not mail me too

      Comment

      • Kyriakos Stavrou

        #4
        Re: Wait for synchronized access

        You should use a monitor. A monitor is a data structure specially designed
        for this purpose.



        An example follows





        private bool status=true;

        public bool Status

        {

        get

        {

        //Locks the object for access only by this thread. This
        means

        //that when the variable status is false monitor is used
        by

        //another thread and the first thread has to wait

        Monitor.Enter(t his);



        if (status==false) Monitor.Wait(th is);



        //When the object is left by the first

        //thread other threads wake up

        Monitor.Pulse(t his);

        //Leaves the object

        Monitor.Exit(th is);

        return status;

        }



        set

        {

        //Locks the object

        Monitor.Enter(t his);

        status=value;

        //Wakes up the other waiting treads

        Monitor.Pulse(t his);

        //Leaves the object

        Monitor.Exit(th is);

        }

        }





        "Roger Down" <roger.down@c2i .net> wrote in message
        news:umUV3e4eDH A.2236@TK2MSFTN GP12.phx.gbl...[color=blue]
        > Lets say I have a method UpdateCache() called from a single thread. I also
        > have a method GetCache() called from multiple threads. When UpdateCache()[/color]
        is[color=blue]
        > called, the cache updating is being processed. This can take time.
        >
        > In the mean time, some of the multiple threads have called GetCache(), but
        > because the cache is being updated, I want them to wait for the
        > UpdateCache() to finish.
        >
        > Something like this, in a very simplified code:
        >
        > public void UpdateCache()
        > {
        > updating = true;
        > try { this.data = GetData(); }
        > finally { updating = false; }
        > }
        >
        > public MyCache GetCache()
        > {
        > while( updating )
        > Thread.Sleep( 200 );
        > return this.data;
        > }
        >
        > If I use lock for obtaining the same functionality, I guess it will be
        > something like this for the UpdateCache() method:
        >
        > public void UpdateCache()
        > {
        > lock(this)
        > {
        > this.data = GetData();
        > }
        > }
        >
        > But how can I rewrite this method ??
        >
        > public MyCache GetCache()
        > {
        > ?????
        > return this.data;
        > }
        >
        > I've seen some examples using Monitor.Enter, Monitor.Wait, Monitor.Pulse[/color]
        and[color=blue]
        > Monitor.Exit on some lockable object before entering a synchronized[/color]
        section[color=blue]
        > of a code... but is there some solution where multiple thread only waits,
        > instead of locking an object ??
        >
        > Maybe there are some better ways to solve this ??
        >
        >
        > Best of regards...
        >
        >[/color]


        Comment

        • Roger Down

          #5
          Re: Wait for synchronized access

          Thanks for the answer, Nicholas... :-)

          Hmm... Let's see if I understand this...

          Using lock(this) on GetCache will make sure of synchronized access to this
          method... but does this mean that every thread is locking the object (or
          some object), before retrieving the "shared" data ?? each thread in sequence
          locks and "unlocks" the object before retrieving the data ?? If so, isn't
          this very slow ??



          Best of regards...



          "Nicholas Paldino [.NET/C# MVP]" wrote:[color=blue]
          > Roger,
          >
          > It's very simple. If you are sure that GetCache and UpdateCache will be
          > called on separate threads, then you can do this:
          >
          > public MyCache GetCache()
          > {
          > // Lock on the same object that updatecache is processing.
          > lock (this)
          > // Return the data.
          > return this.data;
          > }
          >
          > public void UpdateCache()
          > {
          > // Lock on this while updating the data.
          > lock (this)
          > // Update the data.
          > this.data = GetData();
          > }
          >
          > By using the same object in the lock statement, only one thread at a
          > time can access that section of code. So, when UpdateCache is called, if
          > GetCache is called as well, then it will wait until that section of code
          > locked by "this" is exited. Also, if GetCache is called, UpdateCache will
          > not be called until that section in GetCache is exited.
          >
          > Hope this helps.[/color]


          Comment

          • Jon Skeet

            #6
            Re: Wait for synchronized access

            Kyriakos Stavrou <el98610@mail.n tua.gr> wrote:[color=blue]
            > You should use a monitor. A monitor is a data structure specially designed
            > for this purpose.[/color]

            That has the disadvantage of reading threads having to wait for each
            other. A ReaderWriterLoc k removes this problem.

            --
            Jon Skeet - <skeet@pobox.co m>
            Pobox has been discontinued as a separate service, and all existing customers moved to the Fastmail platform.

            If replying to the group, please do not mail me too

            Comment

            • Roger Down

              #7
              Re: Wait for synchronized access

              Hello Jon... :-)

              The ReaderWriterLoc k seems promising... Thanks !!! :-)


              Best of regards...


              "Jon Skeet" wrote in message:[color=blue]
              > Roger Down wrote:[color=green]
              > > Lets say I have a method UpdateCache() called from a single thread. I[/color][/color]
              also[color=blue][color=green]
              > > have a method GetCache() called from multiple threads. When[/color][/color]
              UpdateCache() is[color=blue][color=green]
              > > called, the cache updating is being processed. This can take time.
              > >
              > > In the mean time, some of the multiple threads have called GetCache(),[/color][/color]
              but[color=blue][color=green]
              > > because the cache is being updated, I want them to wait for the
              > > UpdateCache() to finish.
              > >
              > > Something like this, in a very simplified code:[/color]
              >
              > <snip>
              >
              > The first thing to note with your design is that if GetCache is called
              > and then used while you're later updating it, you might have problems.
              >
              > Aside from that, I believe ReaderWriterLoc k is what you're after - have
              > a look for it in MSDN.[/color]


              Comment

              • Nicholas Paldino [.NET/C# MVP]

                #8
                Re: Wait for synchronized access

                Roger,

                It doesn't necessarily block the method, but rather the code in the lock
                statement. Any code that tries to enter the lock block that is locked on a
                particular instance will be blocked out if there is another thread that is
                locked on that same instance. So not only will calls on different threads
                to GetCache blocked, but to UpdateCache as well.

                The ReaderWriterLoc k that Jon Skeet recommended could work for you. The
                only reservation I have about this is the fact that you said that GetCache
                can take a long time.

                Generally speaking, yes, doing locks this way can be slower than
                without, but if used properly, and your application is laid out correctly,
                you can get good performance (as is the case with anything). Also, given
                what you are trying to avoid (corruption of data), I think that it is an
                acceptable loss.


                --
                - Nicholas Paldino [.NET/C# MVP]
                - nicholas.paldin o@exisconsultin g.com


                "Roger Down" <roger.down@c2i .net> wrote in message
                news:%23xbvU44e DHA.2236@TK2MSF TNGP12.phx.gbl. ..[color=blue]
                > Thanks for the answer, Nicholas... :-)
                >
                > Hmm... Let's see if I understand this...
                >
                > Using lock(this) on GetCache will make sure of synchronized access to this
                > method... but does this mean that every thread is locking the object (or
                > some object), before retrieving the "shared" data ?? each thread in[/color]
                sequence[color=blue]
                > locks and "unlocks" the object before retrieving the data ?? If so, isn't
                > this very slow ??
                >
                >
                >
                > Best of regards...
                >
                >
                >
                > "Nicholas Paldino [.NET/C# MVP]" wrote:[color=green]
                > > Roger,
                > >
                > > It's very simple. If you are sure that GetCache and UpdateCache will be
                > > called on separate threads, then you can do this:
                > >
                > > public MyCache GetCache()
                > > {
                > > // Lock on the same object that updatecache is processing.
                > > lock (this)
                > > // Return the data.
                > > return this.data;
                > > }
                > >
                > > public void UpdateCache()
                > > {
                > > // Lock on this while updating the data.
                > > lock (this)
                > > // Update the data.
                > > this.data = GetData();
                > > }
                > >
                > > By using the same object in the lock statement, only one thread at a
                > > time can access that section of code. So, when UpdateCache is called,[/color][/color]
                if[color=blue][color=green]
                > > GetCache is called as well, then it will wait until that section of code
                > > locked by "this" is exited. Also, if GetCache is called, UpdateCache[/color][/color]
                will[color=blue][color=green]
                > > not be called until that section in GetCache is exited.
                > >
                > > Hope this helps.[/color]
                >
                >[/color]


                Comment

                • Lee Alexander

                  #9
                  Re: Wait for synchronized access

                  From what I understand locking 'this' is frowned upon. It's better to hold a
                  private object reference specifically for the locking procedure, that way
                  only the class can lock the resource.

                  private object lockObj = new Object();

                  public MyCache GetCache()
                  {
                  // Lock on the same object that updatecache is processing.
                  lock (lockObj )
                  // Return the data.
                  return this.data;
                  }

                  public void UpdateCache()
                  {
                  // Lock on this while updating the data.
                  lock (lockObj )
                  // Update the data.
                  this.data = GetData();
                  }

                  Anyway as Jon says the reader-writer lock maybe more appropriate.

                  Regards
                  Lee


                  "Nicholas Paldino [.NET/C# MVP]" <nicholas.paldi no@exisconsulti ng.com> wrote
                  in message news:ekuTcl4eDH A.1200@TK2MSFTN GP09.phx.gbl...[color=blue]
                  > Roger,
                  >
                  > It's very simple. If you are sure that GetCache and UpdateCache will[/color]
                  be[color=blue]
                  > called on separate threads, then you can do this:
                  >
                  > public MyCache GetCache()
                  > {
                  > // Lock on the same object that updatecache is processing.
                  > lock (this)
                  > // Return the data.
                  > return this.data;
                  > }
                  >
                  > public void UpdateCache()
                  > {
                  > // Lock on this while updating the data.
                  > lock (this)
                  > // Update the data.
                  > this.data = GetData();
                  > }
                  >
                  > By using the same object in the lock statement, only one thread at a
                  > time can access that section of code. So, when UpdateCache is called, if
                  > GetCache is called as well, then it will wait until that section of code
                  > locked by "this" is exited. Also, if GetCache is called, UpdateCache will
                  > not be called until that section in GetCache is exited.
                  >
                  > Hope this helps.
                  >
                  >
                  > --
                  > - Nicholas Paldino [.NET/C# MVP]
                  > - nicholas.paldin o@exisconsultin g.com
                  >
                  > "Roger Down" <roger.down@c2i .net> wrote in message
                  > news:umUV3e4eDH A.2236@TK2MSFTN GP12.phx.gbl...[color=green]
                  > > Lets say I have a method UpdateCache() called from a single thread. I[/color][/color]
                  also[color=blue][color=green]
                  > > have a method GetCache() called from multiple threads. When[/color][/color]
                  UpdateCache()[color=blue]
                  > is[color=green]
                  > > called, the cache updating is being processed. This can take time.
                  > >
                  > > In the mean time, some of the multiple threads have called GetCache(),[/color][/color]
                  but[color=blue][color=green]
                  > > because the cache is being updated, I want them to wait for the
                  > > UpdateCache() to finish.
                  > >
                  > > Something like this, in a very simplified code:
                  > >
                  > > public void UpdateCache()
                  > > {
                  > > updating = true;
                  > > try { this.data = GetData(); }
                  > > finally { updating = false; }
                  > > }
                  > >
                  > > public MyCache GetCache()
                  > > {
                  > > while( updating )
                  > > Thread.Sleep( 200 );
                  > > return this.data;
                  > > }
                  > >
                  > > If I use lock for obtaining the same functionality, I guess it will be
                  > > something like this for the UpdateCache() method:
                  > >
                  > > public void UpdateCache()
                  > > {
                  > > lock(this)
                  > > {
                  > > this.data = GetData();
                  > > }
                  > > }
                  > >
                  > > But how can I rewrite this method ??
                  > >
                  > > public MyCache GetCache()
                  > > {
                  > > ?????
                  > > return this.data;
                  > > }
                  > >
                  > > I've seen some examples using Monitor.Enter, Monitor.Wait, Monitor.Pulse[/color]
                  > and[color=green]
                  > > Monitor.Exit on some lockable object before entering a synchronized[/color]
                  > section[color=green]
                  > > of a code... but is there some solution where multiple thread only[/color][/color]
                  waits,[color=blue][color=green]
                  > > instead of locking an object ??
                  > >
                  > > Maybe there are some better ways to solve this ??
                  > >
                  > >
                  > > Best of regards...
                  > >
                  > >[/color]
                  >
                  >[/color]


                  Comment

                  • Horatiu Ripa

                    #10
                    Re: Wait for synchronized access

                    Let's have a system in thinking:

                    1. Identify the critical section
                    - The critical sections are[color=blue][color=green]
                    > > return this.data;
                    > > this.data = GetData();[/color][/color]
                    since they are accessing the shared resource (this.data)

                    2. Now let's syncronize them around the critical section:

                    - It is not so bad to lock all the object. Why? Because all the threads
                    will wait for one thread to execute just one operation (return... or
                    GetData), but this is only in this simple code. Drawback: the other threads
                    must wait until the thread that puts the lock exits the critical section
                    REGARDLESS the fact that they want or not to access the critical section!
                    - A better choice is to have some locking object (let's name it
                    lockingObject) declared of some type (not primitive) and instantiated in
                    your class. Then what will happen if you'll lock the "lockingObj ect" instead
                    of "this"?
                    Let's say that the thread that populates the value enters the critical
                    section. The lock is placed on the lockObject and all other threads, as long
                    as they won't access the lockObject members or try to lock the lockObject
                    will work. In that manner you isolate only the critical section in the
                    syncronization.

                    --
                    Horatiu Ripa
                    Software Development Manager
                    Business Logic Systems LTD
                    21 Victor Babes str., 1st floor, 3400 Cluj-Napoca, Romania
                    Phone/Fax: +40 264 590703
                    Web: www.businesslogic.co.uk

                    This email (email message and any attachments) is strictly confidential,
                    possibly privileged and is intended solely for the person or organization to
                    whom it is addressed. If you are not the intended recipient, you must not
                    copy, distribute or take any action in reliance on it. If you have received
                    this email in error, please inform the sender immediately before deleting
                    it. Business Logic Systems Ltd accepts no responsibility for any advice,
                    opinion, conclusion or other information contained in this email or arising
                    from its disclosure.

                    "Roger Down" <roger.down@c2i .net> wrote in message
                    news:#xbvU44eDH A.2236@TK2MSFTN GP12.phx.gbl...[color=blue]
                    > Thanks for the answer, Nicholas... :-)
                    >
                    > Hmm... Let's see if I understand this...
                    >
                    > Using lock(this) on GetCache will make sure of synchronized access to this
                    > method... but does this mean that every thread is locking the object (or
                    > some object), before retrieving the "shared" data ?? each thread in[/color]
                    sequence[color=blue]
                    > locks and "unlocks" the object before retrieving the data ?? If so, isn't
                    > this very slow ??
                    >
                    >
                    >
                    > Best of regards...
                    >
                    >
                    >
                    > "Nicholas Paldino [.NET/C# MVP]" wrote:[color=green]
                    > > Roger,
                    > >
                    > > It's very simple. If you are sure that GetCache and UpdateCache will be
                    > > called on separate threads, then you can do this:
                    > >
                    > > public MyCache GetCache()
                    > > {
                    > > // Lock on the same object that updatecache is processing.
                    > > lock (this)
                    > > // Return the data.
                    > > return this.data;
                    > > }
                    > >
                    > > public void UpdateCache()
                    > > {
                    > > // Lock on this while updating the data.
                    > > lock (this)
                    > > // Update the data.
                    > > this.data = GetData();
                    > > }
                    > >
                    > > By using the same object in the lock statement, only one thread at a
                    > > time can access that section of code. So, when UpdateCache is called,[/color][/color]
                    if[color=blue][color=green]
                    > > GetCache is called as well, then it will wait until that section of code
                    > > locked by "this" is exited. Also, if GetCache is called, UpdateCache[/color][/color]
                    will[color=blue][color=green]
                    > > not be called until that section in GetCache is exited.
                    > >
                    > > Hope this helps.[/color]
                    >
                    >[/color]


                    Comment

                    Working...