473,396 Members | 1,918 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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...
Nov 15 '05 #1
9 1698
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]
- ni**************@exisconsulting.com

"Roger Down" <ro********@c2i.net> wrote in message
news:um**************@TK2MSFTNGP12.phx.gbl...
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...

Nov 15 '05 #2
Roger Down <ro********@c2i.net> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #3
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);

}

}

"Roger Down" <ro********@c2i.net> wrote in message
news:um**************@TK2MSFTNGP12.phx.gbl...
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...

Nov 15 '05 #4
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:
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.

Nov 15 '05 #5
Kyriakos Stavrou <el*****@mail.ntua.gr> wrote:
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.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #6
Hello Jon... :-)

The ReaderWriterLock seems promising... Thanks !!! :-)
Best of regards...
"Jon Skeet" wrote in message:
Roger Down wrote:
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.

Nov 15 '05 #7
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]
- ni**************@exisconsulting.com
"Roger Down" <ro********@c2i.net> wrote in message
news:%2****************@TK2MSFTNGP12.phx.gbl...
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:
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.


Nov 15 '05 #8
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]" <ni**************@exisconsulting.com> wrote
in message news:ek**************@TK2MSFTNGP09.phx.gbl...
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]
- ni**************@exisconsulting.com

"Roger Down" <ro********@c2i.net> wrote in message
news:um**************@TK2MSFTNGP12.phx.gbl...
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...


Nov 15 '05 #9
Let's have a system in thinking:

1. Identify the critical section
- The critical sections are
return this.data;
this.data = GetData(); 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 "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" <ro********@c2i.net> wrote in message
news:#x**************@TK2MSFTNGP12.phx.gbl...
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:
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.


Nov 15 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Vespasian | last post by:
notify() and wait() throw an exception if the calling thread does not own the object's monitor. Does this imply that the check is made at runtime, and if so, why can't it be made at compile time? ...
2
by: Urs Vogel | last post by:
Hi I'm using static, synchronized Hashtables: static Hashtable _htDiags = new Hashtable(); static Hashtable htDiags = Hashtable.Synchronized(_htDiags); I'm not totally sure, if this...
1
by: KK | last post by:
Dear All I have a class whose methods are getting called from multiple threads in my application. For example class DataDistribution { private ArrayList datset; public DataDistribution() {...
3
by: Ryan Liu | last post by:
Hi, What does ArrayList.Synchronized really do for an ArrayList? Is that equal to add lock(this) for all its public methods and properties? Not just for Add()/Insert()/Remvoe()/Count, but also...
12
by: Perecli Manole | last post by:
I am having some strange thread synchronization problems that require me to better understand the intricacies of Monitor.Wait/Pulse. I have 3 threads. Thread 1 does a Monitor.Wait in a SyncLock...
2
by: semedao | last post by:
Hi, what is the best way to Synchronized threads on classes that use or inherit from Generics ? (Dictionary for example) Thanks. (and where is the *Class*.Synchronized method for them ?)
5
by: cozsmin | last post by:
hello , as u know wait() and notify() will not thow an exception if the method that calls them has the lock , or esle i misundrestood java :P this is the code that throws (unwanted) ...
1
by: MessyHeart | last post by:
The documentation on MSDN for the overloaded Monitor.wait(object,timespan, bool) is: public static bool Wait( Object obj, TimeSpan timeout, bool exitContext ) Releases the lock...
2
by: greyradio | last post by:
I've recently have been given an assignment to do and it seems that notify() does notify() any of the waiting threads. The project entails 10 commuters and two different toll booths. The EZPass booth...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.