473,386 Members | 1,803 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,386 software developers and data experts.

Locking Question around hashtable

In csharp, what is the correct locking around reading and writing into
a hashtable. Note that the reader is not looping through the keys,
simply reading an item out with a specific key:

If i have the following hashtable h which has multiple readers and 1
writer (on different threads) is this the correct locking below:

[Reader]
lock (h.syncroot)
{
string r = h["Test"];
}
msgbox r;

[Writer]
string w = "Mike";
lock (h.syncroot)
{
h["Test"] = w;
}

Feb 13 '06 #1
16 3428
ak*********@hotmail.com wrote:
In csharp, what is the correct locking around reading and writing into
a hashtable. Note that the reader is not looping through the keys,
simply reading an item out with a specific key:

If i have the following hashtable h which has multiple readers and 1
writer (on different threads) is this the correct locking below:


<snip>

If you've just got a single writer and multiple readers, the
documentation states that you don't need any locking. However, I
suspect you *do* need locking if you want to make absolutely sure that
a reader will always see a writer's last write.

You could use a ReaderWriterLock for this, although others who have
used this (at least in 1.1 - not sure if it's fixed in 2.0 or not) have
said that ReaderWriterLock is so slow that it's usually much faster
just to take an exclusive lock every time (in which case your code is
fine).

Jon

Feb 13 '06 #2
thanks for the response . .heres another followup question:

Lets say i have have a hashtable of hashtables (again on multiple
threads where there is one writer and multiple readers . .)

what would be the correct locking around the code below.

[Reader]
Hashtable n = h["Test'];
string Name = n["Joe"];

[Writer]
hash.Add("Joe", true);
h["Test"] = hash;
Jon Skeet [C# MVP] wrote:
ak*********@hotmail.com wrote:
In csharp, what is the correct locking around reading and writing into
a hashtable. Note that the reader is not looping through the keys,
simply reading an item out with a specific key:

If i have the following hashtable h which has multiple readers and 1
writer (on different threads) is this the correct locking below:


<snip>

If you've just got a single writer and multiple readers, the
documentation states that you don't need any locking. However, I
suspect you *do* need locking if you want to make absolutely sure that
a reader will always see a writer's last write.

You could use a ReaderWriterLock for this, although others who have
used this (at least in 1.1 - not sure if it's fixed in 2.0 or not) have
said that ReaderWriterLock is so slow that it's usually much faster
just to take an exclusive lock every time (in which case your code is
fine).

Jon


Feb 13 '06 #3
I recomend (till J Skeet did't come and criticise me :)) to use ReaderWriter
lock if only one writer and several readers

Using the ReaderWriterLock class, any number of threads can safely read data
concurrently. Only when threads are updating is data locked. Reader threads
can acquire a lock only if there are no writers holding the lock. Writer
threads can acquire lock only if there are no readers or writers holding the
lock.

public class ReadWrite
{
private ReaderWriterLock rwl;
private HashTable h;

public ReadWrite()
{
rwl = new ReaderWriterLock();
}

public void ReadInts(ref int a, ref int b)
{
rwl.AcquireReaderLock(Timeout.Infinite);
try
{
string r = h["Test"];
}
finally
{
rwl.ReleaseReaderLock();
}
}

public void WriteInts(int a, int b)
{
rwl.AcquireWriterLock(Timeout.Infinite);

try
{
string w = "Mike";
h["Test"] = w;
}
finally
{
rwl.ReleaseWriterLock();
}
}
}

"ak*********@hotmail.com" wrote:
In csharp, what is the correct locking around reading and writing into
a hashtable. Note that the reader is not looping through the keys,
simply reading an item out with a specific key:

If i have the following hashtable h which has multiple readers and 1
writer (on different threads) is this the correct locking below:


--
WBR,
Michael Nemtsev :: blog: http://spaces.msn.com/laflour

"At times one remains faithful to a cause only because its opponents do not
cease to be insipid." (c) Friedrich Nietzsche

Feb 13 '06 #4
> You could use a ReaderWriterLock for this, although others who have
used this (at least in 1.1 - not sure if it's fixed in 2.0 or not) have
said that ReaderWriterLock is so slow that it's usually much faster
just to take an exclusive lock every time (in which case your code is
fine).


I would like to back this statement with personal experience from a
framework that had to support locking of shared resources. We first went
with the ReaderWriterLock but resorted to the lock() statement, because it
was a lot faster (and I really mean a lot).

--
With regards
Anders Borum / SphereWorks
Microsoft Certified Professional (.NET MCP)
Feb 13 '06 #5

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
ak*********@hotmail.com wrote:
In csharp, what is the correct locking around reading and writing into
a hashtable. Note that the reader is not looping through the keys,
simply reading an item out with a specific key:

If i have the following hashtable h which has multiple readers and 1
writer (on different threads) is this the correct locking below:


<snip>

If you've just got a single writer and multiple readers, the
documentation states that you don't need any locking.


Which documentation?

QUOTE
Thread Safety
To support one or more writers, all operations on the Hashtable must be done
through the wrapper returned by the Synchronized method.

UNQUOTE
Feb 13 '06 #6
Nick Hounsome wrote:
If you've just got a single writer and multiple readers, the
documentation states that you don't need any locking.


Which documentation?

QUOTE
Thread Safety
To support one or more writers, all operations on the Hashtable must be done
through the wrapper returned by the Synchronized method.
UNQUOTE


Good question. I *know* that the documentation did at one stage say
that it was safe for a single writer and multiple readers - but I can't
find it now :(

(I seem to remember that at the time that it said it was safe in that
way, the Thread Safety section itself was the standard "instance
members aren't threadsafe" docs, so it was already self-contradictory.)

Jon

Feb 13 '06 #7

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
Nick Hounsome wrote:
> If you've just got a single writer and multiple readers, the
> documentation states that you don't need any locking.


Which documentation?

QUOTE
Thread Safety
To support one or more writers, all operations on the Hashtable must be
done
through the wrapper returned by the Synchronized method.
UNQUOTE


Good question. I *know* that the documentation did at one stage say
that it was safe for a single writer and multiple readers - but I can't
find it now :(

(I seem to remember that at the time that it said it was safe in that
way, the Thread Safety section itself was the standard "instance
members aren't threadsafe" docs, so it was already self-contradictory.)


You should be OK(ish) provided that you don't add or remove items.
Reading or changing (h[a]=b) should probably be alright but things would go
horribly wrong if a bucket was added or an element chained whilst a read was
in progress without some locking
Feb 13 '06 #8
"Jon Skeet [C# MVP]" wrote:
Nick Hounsome wrote:
If you've just got a single writer and multiple readers, the
documentation states that you don't need any locking.


Which documentation?

Good question. I *know* that the documentation did at one stage say
that it was safe for a single writer and multiple readers - but I can't
find it now :(


Maybe I've read abt ReaderWriterLock? Coz it's stated in MSDN that this type
is safe for multithreaded operations
Feb 13 '06 #9

"Michael Nemtsev" <Mi************@discussions.microsoft.com> wrote in
message news:53**********************************@microsof t.com...
"Jon Skeet [C# MVP]" wrote:
Nick Hounsome wrote:
> > If you've just got a single writer and multiple readers, the
> > documentation states that you don't need any locking.
>
> Which documentation?

Good question. I *know* that the documentation did at one stage say
that it was safe for a single writer and multiple readers - but I can't
find it now :(


Maybe I've read abt ReaderWriterLock? Coz it's stated in MSDN that this
type
is safe for multithreaded operations


It is but we were talking about a bare Hashtable

Also what Jon said about RW locks is generally true - if you are just doing
simple access then locking the whole thing is going to be quicker and
easier - RW locks are only worthwhile if the readers are spending a lot of
time rummaging around in a data structure - tree walking would be the most
common use.
Feb 13 '06 #10
Nick Hounsome wrote:
Good question. I *know* that the documentation did at one stage say
that it was safe for a single writer and multiple readers - but I can't
find it now :(

(I seem to remember that at the time that it said it was safe in that
way, the Thread Safety section itself was the standard "instance
members aren't threadsafe" docs, so it was already self-contradictory.)


You should be OK(ish) provided that you don't add or remove items.
Reading or changing (h[a]=b) should probably be alright but things would go
horribly wrong if a bucket was added or an element chained whilst a read was
in progress without some locking


I looked into it a little while ago, and I *think* I came to the
conclusion that the way it was written, even additions and removals
would be okay so long as you genuinely only had a single writer - you
just wouldn't see modifications until the reading thread picked up the
potentially new bucket structure.

Then again, I'm not an expert in hashtable implementations by any
stretch of the imagination (and in my experience people are willing to
stretch their imaginations a long way when it comes to calling someone
an expert). I personally wouldn't normally trust it, but then I'm
pretty paranoid when it comes to threading...

Jon

Feb 13 '06 #11
I'll back that statement about the HORRENDOUS performance of the
ReaderWriterLock class.

Also, this was NOT fixed in 2.0. Maybe 3.0?

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com...
ak*********@hotmail.com wrote:
In csharp, what is the correct locking around reading and writing into
a hashtable. Note that the reader is not looping through the keys,
simply reading an item out with a specific key:

If i have the following hashtable h which has multiple readers and 1
writer (on different threads) is this the correct locking below:


<snip>

If you've just got a single writer and multiple readers, the
documentation states that you don't need any locking. However, I
suspect you *do* need locking if you want to make absolutely sure that
a reader will always see a writer's last write.

You could use a ReaderWriterLock for this, although others who have
used this (at least in 1.1 - not sure if it's fixed in 2.0 or not) have
said that ReaderWriterLock is so slow that it's usually much faster
just to take an exclusive lock every time (in which case your code is
fine).

Jon

Feb 13 '06 #12
Nicholas Paldino [.NET/C# MVP] wrote:
I'll back that statement about the HORRENDOUS performance of the
ReaderWriterLock class.
Indeed, it was mostly you I was thinking of :)
Also, this was NOT fixed in 2.0. Maybe 3.0?


That's useful (I originally wrote 'good', but then thought better of
it) to know. Someone pester me if I haven't written up a few tests etc
about it in my threading tutorial some time in the next week...

Jon

Feb 13 '06 #13

Anders Borum wrote:
You could use a ReaderWriterLock for this, although others who have
used this (at least in 1.1 - not sure if it's fixed in 2.0 or not) have
said that ReaderWriterLock is so slow that it's usually much faster
just to take an exclusive lock every time (in which case your code is
fine).


I would like to back this statement with personal experience from a
framework that had to support locking of shared resources. We first went
with the ReaderWriterLock but resorted to the lock() statement, because it
was a lot faster (and I really mean a lot).


I typically avoid the ReaderWriterLock altogether. Threading is
already hard enough so I try to keep things simple at the expense of
performance. There is a better chance that I'll make a mistake if I
try to get too fancy with it. And, as you pointed out, the
ReaderWriterLock only performs better in a limited number of scenarios
anyway.

Brian

Feb 13 '06 #14
Brian Gideon wrote:
I typically avoid the ReaderWriterLock altogether. Threading is
already hard enough so I try to keep things simple at the expense of
performance. There is a better chance that I'll make a mistake if I
try to get too fancy with it.


That is absolutely the best policy, IMO. When in doubt, keep it simple.
Performance problems are very rarely where people expect them to be
anyway :)

Jon

Feb 13 '06 #15
<ak*********@hotmail.com> wrote:
thanks for the response . .heres another followup question:

Lets say i have have a hashtable of hashtables (again on multiple
threads where there is one writer and multiple readers . .)

what would be the correct locking around the code below.

[Reader]
Hashtable n = h["Test'];
string Name = n["Joe"];

[Writer]
hash.Add("Joe", true);
h["Test"] = hash;


Well, what level of atomicity do you need? Is it important to you that
nothing "interrupts" the two operations in each case? If not, just lock
each statement:

Hashtable n;
lock (h.SyncRoot)
{
n = (Hashtable) h["Test"];
}
string name;
lock (n.SyncRoot)
{
name = (string) n["Joe"];
}

(and likewise for the write).

If you *do* need to make the pair of reads/writes truly atomic, you
need to nest the locks - but make sure you always acquire them and
release them in the same order wherever you use them, otherwise you'll
get a deadlock!

It may well be simpler in that situation to use a single lock which is
always acquired when using either hashtable...

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Feb 13 '06 #16
WXS
Some interesting info for people using hashtables:
1. When threading use the synchronized hastable wrapper if you are not
worried about not seeing writes immediately when done from another thread.
2. The synchronized hashtable only locks on deletions internally as it
copies buckets normal to avoid locking
3. Given the above implementation it is slow, but provides good parallelism
and reduced contention
4. Given #1 is ok for you, you only need to lock if you need to enumerate
all of the elements in the hashtable since the enmerator is not thread safe.
5. For even higher performance given a well known dataset and using strings
as keys you might try a different hash algorithm, the MS one is nicely
distributed producing few collisions but is slow compared to other algorithms
that would produce more collisions for large data sets, but if your data set
is well known or small and diverse some more simplistic algorithms may work
for you.
This is based on a rough idea of .NET 1.1, examining through reflector and
such.
Obviously these internals may change in future versions.

"Jon Skeet [C# MVP]" wrote:
Nicholas Paldino [.NET/C# MVP] wrote:
I'll back that statement about the HORRENDOUS performance of the
ReaderWriterLock class.


Indeed, it was mostly you I was thinking of :)
Also, this was NOT fixed in 2.0. Maybe 3.0?


That's useful (I originally wrote 'good', but then thought better of
it) to know. Someone pester me if I haven't written up a few tests etc
about it in my threading tutorial some time in the next week...

Jon

Mar 14 '06 #17

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

Similar topics

4
by: Sam | last post by:
Hello everyone, I have around 20 reports in an ASP web-application which connects to a SQL Server 2000 dB, executes stored procedures based on input parameters and returns the data in a nice...
2
by: Deano | last post by:
I use the Access 2000 MSI Wizard from Sagekey and they don't know if the bug documented on page 32 of the Access 2000 Developer`s Handbook Volume 2: Enterprise Edition still affects the runtime. ...
5
by: swapna_munukoti | last post by:
Hi all, Is there any tool to achieve record locking in MS Access 2000. Thanks, Swapna.
5
by: francois | last post by:
First of all I would to to apologize for resending this post again but I feel like my last post as been spoiled Here I go for my problem: Hi, I have a webservice that I am using and I would...
15
by: z. f. | last post by:
Hi, i have an ASP.NET project that is using a (Class Library Project) VB.NET DLL. for some reason after running some pages on the web server, and trying to compile the Class Library DLL, it...
9
by: master | last post by:
Actually, it is not only the record locking, what I need, and nobody seems to descibe this. Imagine the following scenario. There is a database with, say 10000 records with some unvalidated...
5
by: Chris Mullins | last post by:
I've spent some time recently looking into optimizing some memory usage in our products. Much of this was doing through the use of string Interning. I spent the time and checked numbers in both x86...
4
by: Mark S. | last post by:
Much to my surprised the code below compiled and ran. I just don't know enough about threading to know for sure if this is too good to be true. I'm attempting to isolate the Hashtable lock to...
1
by: polastine | last post by:
Hi Anthony -- Anthony Jones wrote: OK, figured as much. I'm not forking any threads myself. 2.0, currently. Why? Is there a difference/advantage? I can probably go to 3.x if there's a...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.