473,698 Members | 2,467 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 3459
ak*********@hot mail.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 ReaderWriterLoc k 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 ReaderWriterLoc k 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*********@hot mail.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 ReaderWriterLoc k 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 ReaderWriterLoc k 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 ReaderWriterLoc k 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 ReaderWriterLoc k rwl;
private HashTable h;

public ReadWrite()
{
rwl = new ReaderWriterLoc k();
}

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

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

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

"ak*********@ho tmail.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 ReaderWriterLoc k 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 ReaderWriterLoc k 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 ReaderWriterLoc k 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.co m> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com.. .
ak*********@hot mail.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.co m> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.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 ReaderWriterLoc k? Coz it's stated in MSDN that this type
is safe for multithreaded operations
Feb 13 '06 #9

"Michael Nemtsev" <Mi************ @discussions.mi crosoft.com> wrote in
message news:53******** *************** ***********@mic rosoft.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 ReaderWriterLoc k? 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

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

Similar topics

4
3504
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 tabular format. The data which is used in these reports actually originates from a 3rd party accounting application called Exchequer. I have written a VB application (I call it the extractor) which extracts data from Exchequer and dumps the same...
2
2215
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. Apparently page locking is invoked when using the Access run-time record than record-level locking. This also affects Access 2000 but if you patch Access the bug is fixed. I really don't know about the runtime though. Does anyone know if...
5
2357
by: swapna_munukoti | last post by:
Hi all, Is there any tool to achieve record locking in MS Access 2000. Thanks, Swapna.
5
2819
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 like it to return an XML serialized version of an object.
15
6192
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 can't compile because the DLL is in use (and the PDB too), and the w3wp.exe process is the process locking the DLL (as viewed with Sysinternals - Process Explorer). this is a huge problem. i need to do IIS reset in order to free the DLL! 1. why is...
9
2651
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 data. And there is an Intranet ASP.NET application which is an interface to the database in question... and there are 100 pretty girls eager to... uhmm... use the application and validate the data of course ;-). The task is to enable the data...
5
1702
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 and x64, and have published the results here: http://www.coversant.com/dotnetnuke/Default.aspx?tabid=88&EntryID=24 The benefits for our SoapBox suite of products are pretty compelling, memory wise. Before I roll the changes into our...
4
1668
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 "row level", the whys aren't important at this time. Does this code actually do what I want? using System; using System.Collections; using System.Collections.Generic; using System.Text;
1
1452
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 good reason for it.
0
8678
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8609
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9166
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9030
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8871
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7737
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5861
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4371
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4621
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.