Wait for synchronized access

R

Roger Down

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...
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 
J

Jon Skeet

Roger Down said:
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:

<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 ReaderWriterLock is what you're after - have
a look for it in MSDN.
 
K

Kyriakos Stavrou

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(this);



if (status==false) Monitor.Wait(this);



//When the object is left by the first

//thread other threads wake up

Monitor.Pulse(this);

//Leaves the object

Monitor.Exit(this);

return status;

}



set

{

//Locks the object

Monitor.Enter(this);

status=value;

//Wakes up the other waiting treads

Monitor.Pulse(this);

//Leaves the object

Monitor.Exit(this);

}

}
 
R

Roger Down

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...
 
J

Jon Skeet

Kyriakos Stavrou said:
You should use a monitor. A monitor is a data structure specially designed
for this purpose.

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

Roger Down

Hello Jon... :)

The ReaderWriterLock seems promising... Thanks !!! :)


Best of regards...
 
N

Nicholas Paldino [.NET/C# MVP]

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 ReaderWriterLock 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]
- (e-mail address removed)


Roger Down said:
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]" said:
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.
 
L

Lee Alexander

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 said:
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]
- (e-mail address removed)

Roger Down said:
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...
 
H

Horatiu Ripa

Let's have a system in thinking:

1. Identify the critical section
- The critical sections aresince 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 "lockingObject" 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 said:
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]" said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top