473,657 Members | 2,517 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

read lock needed?

Hi,

If I have many threads write to a variable(e.g. var++) and another thread
read it on an interval base.

For those writing thread, I know I need lock, or its value could be lower
( even I think it is mostly not going to happen for ++ operation since it is
not something like read a value and wait sometime then write back in
multiple threading environment, BTW, is this understanding right?).

My question, for the reading thread, do I need lock?
If a lock is still a must, what about when I can accept race condition,
just the read value don't to be "too old", e.g. 2 or more less than the its
current value. And new read should never less then old read.

If I don't use lock in read thread, do I have to use volatile for the var,
otherwise it has the potential not to read the current value?

Thanks a lot!
Dec 16 '06 #1
17 5402
Ryan Liu wrote:
Hi,

If I have many threads write to a variable(e.g. var++) and another thread
read it on an interval base.

For those writing thread, I know I need lock, or its value could be lower
( even I think it is mostly not going to happen for ++ operation since it is
not something like read a value and wait sometime then write back in
multiple threading environment, BTW, is this understanding right?).
The ++ operator does not produce an atomic read-increment-write action
so it certainly is possible that you'd see a lower (or possibly higher)
value for the variable than what it's suppose to be.
My question, for the reading thread, do I need lock?
Well, technically no. At the very least you do need to use one of the
volatile read mechanisms, but it's best if you go ahead and use a lock
especially if you're already using them for the writing threads.
If a lock is still a must, what about when I can accept race condition,
just the read value don't to be "too old", e.g. 2 or more less than the its
current value. And new read should never less then old read.
That's impossible if you use locks correctly.
If I don't use lock in read thread, do I have to use volatile for the var,
otherwise it has the potential not to read the current value?
That's correct. But again, I'd use a lock

Dec 16 '06 #2
Ryan Liu <ad********@onl ine.sh.cnwrote:
If I have many threads write to a variable(e.g. var++) and another thread
read it on an interval base.

For those writing thread, I know I need lock, or its value could be lower
( even I think it is mostly not going to happen for ++ operation since it is
not something like read a value and wait sometime then write back in
multiple threading environment, BTW, is this understanding right?).

My question, for the reading thread, do I need lock?
Yes, if you want to make sure you see a recent value.
If a lock is still a must, what about when I can accept race condition,
just the read value don't to be "too old", e.g. 2 or more less than the its
current value. And new read should never less then old read.
Within one thread, I don't *think* you should ever see one value
followed by a smaller one. Within multiple threads you could.
If I don't use lock in read thread, do I have to use volatile for the var,
otherwise it has the potential not to read the current value?
Using volatile would mean you wouldn't need to lock the reading thread.

An alternative is to use Thread.MemoryBa rrier().

However, I'd suggest just using the lock for all access to the
variable: do you have any evidence to suggest this would be a bad idea?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 16 '06 #3

"Jon Skeet [C# MVP]" <sk***@pobox.co m????
news:MP******** *************** *@msnews.micros oft.com...
Ryan Liu <ad********@onl ine.sh.cnwrote:
If I have many threads write to a variable(e.g. var++) and another
thread
read it on an interval base.

For those writing thread, I know I need lock, or its value could be
lower
( even I think it is mostly not going to happen for ++ operation since
it is
not something like read a value and wait sometime then write back in
multiple threading environment, BTW, is this understanding right?).

My question, for the reading thread, do I need lock?

Yes, if you want to make sure you see a recent value.
If a lock is still a must, what about when I can accept race condition,
just the read value don't to be "too old", e.g. 2 or more less than the
its
current value. And new read should never less then old read.

Within one thread, I don't *think* you should ever see one value
followed by a smaller one. Within multiple threads you could.
If I don't use lock in read thread, do I have to use volatile for the
var,
otherwise it has the potential not to read the current value?

Using volatile would mean you wouldn't need to lock the reading thread.

An alternative is to use Thread.MemoryBa rrier().

However, I'd suggest just using the lock for all access to the
variable: do you have any evidence to suggest this would be a bad idea?

Actually, no. I just though lock might more costly than volatile. This is a
client/server appliction, I am expect one day to support 500
clients(threads ) at the same time.

Thanks, Jon!

Ryan

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too

Dec 16 '06 #4

Ryan Liu wrote:
Actually, no. I just though lock might more costly than volatile.
I suppose it is in most circumstances, but have you benchmarked a lock?
I think you might be surprised by how fast it is. Also, it may seem
counter intuitive, but some lock-free strategies can actually be
slower.
>This is a
client/server appliction, I am expect one day to support 500
clients(threads ) at the same time.
500 isn't a lot, but if you're mapping them 1-to-1 onto threads then
you're choosing a suboptimal design.

Brian

Dec 16 '06 #5
Ryan Liu <ad********@onl ine.sh.cnwrote:
However, I'd suggest just using the lock for all access to the
variable: do you have any evidence to suggest this would be a bad idea?

Actually, no. I just though lock might more costly than volatile.
Yes, it is.
This is a client/server appliction, I am expect one day to support 500
clients(threads ) at the same time.
I would anticipate that the cost of locking will still be insignificant
compared with other costs. If the code runs sluggishly with a high
number of threads, profile it and see whether the locks are the
problem. Basically, stick to a simple solution until there's a reason
to move away from it.

(You may well want to consider moving to a model with fewer threads and
asynchronous operations at that point as an alternative strategy, btw.)

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Dec 16 '06 #6
Thanks Jon and Brian,

I am happy both of you mention the design paten for threading.

Can I ask 4 more questions?

1: Is 500 threads considered a lot? Can a cheap or regular server with 2.0G
Hz CPU, 512M-1G server handle it?

2: Client and serer are sending data though TcpClient all the time(real time
short messages), so it is always on connection (I do this or other client
has network problem from time to time in a 60 clients environment). So on
server side, I have one thread for each client and sit on the socket to keep
receiving data from client.

I can not think a way to reduce thread in this situation. Can you give me
some insights?

3: BTW, maybe it is even worse design: to make my job easier, not just
server connect to db, all clients connect to db directly as well. So db
server (most time is on the same machine as application server) also keep
hundreds db connection open. What are the better design for this?

4: You have mentioned benchmark or profile, actually what are the better
tools to do so? And what are the common (free) tools to mointor resource use
and to check network traffic(load/data)?

That are lots of questions. Thanks a lot for any help from you or others in
the group!!

Ryan

"Brian Gideon" <br*********@ya hoo.com????
news:11******** **************@ 73g2000cwn.goog legroups.com...
>
Ryan Liu wrote:
Actually, no. I just though lock might more costly than volatile.

I suppose it is in most circumstances, but have you benchmarked a lock?
I think you might be surprised by how fast it is. Also, it may seem
counter intuitive, but some lock-free strategies can actually be
slower.
This is a
client/server appliction, I am expect one day to support 500
clients(threads ) at the same time.

500 isn't a lot, but if you're mapping them 1-to-1 onto threads then
you're choosing a suboptimal design.

Brian

Dec 17 '06 #7
"Ryan Liu" <ad********@onl ine.sh.cnwrote:
>1: Is 500 threads considered a lot? Can a cheap or regular server with 2.0G
Hz CPU, 512M-1G server handle it?
500 threads are a heck of a lot, especially if they're all active
(i.e. not all blocked).

Each thread by default takes up 1mb of virtual address space for its
stack. So straight off the bat you've wasted 500mb of addres space
(out of a total of only 2gb).

Moreover, their stacks will be scattered over memory, so each context
switch will mean that the cache is useless, so you'll get very bad
cache performance.

Finally, my memory is that each call to CreateThread involves
inter-process communication with one of the windows DLLs (smss?) and
it does this so the OS can keep a track of all threads and tidy them
up when a process terminates. IPC is always slowish.

If your hardware has N cores, then you will always lose performance if
you have more than N active threads.

The only reason to have lots of threads is because it makes your
program logic easier, and because you want your code to run on future
manycore machines without recompilation. Does 500 threads really make
your code easier to design, understand and debug? it's hard to
believe...
--
Lucian
Dec 17 '06 #8
The only reason to have lots of threads is because it makes your
program logic easier, and because you want your code to run on future
manycore machines without recompilation
That is not the reason to be using threads, I am not sure many people
compile their code thinking it will run faster on multi-core machines in the
future, basicially using a number of threads is useful even on a single core
machine because they improve throughput of your program, if you have many
jobs to process and were doing it serially then if you come across a large
job that takes a long time many smaller jobs have to wait for the large job
to complete, however with threads you can let multiple threads process jobs
pseudo simultaneously so you can process more jobs in the same time. Given
that with 1 core there is really only one thread running at any one time but
because you are allowing multiple items to be processed in a given time it is
a better strategy.

Also threads can help give a "perceived" speed increase, for example loading
a program at the beginning you can allow people to start using the program
while other threads are loading data/initializing in the background.
Although these tasks still take the same amount fof time (or even more due to
multiple context switching) as if you had executed them serially to the user
the program is perceived as loading faster because they can use it quicker.

Mark.
--
http://www.markdawson.org
"Lucian Wischik" wrote:
"Ryan Liu" <ad********@onl ine.sh.cnwrote:
1: Is 500 threads considered a lot? Can a cheap or regular server with 2.0G
Hz CPU, 512M-1G server handle it?

500 threads are a heck of a lot, especially if they're all active
(i.e. not all blocked).

Each thread by default takes up 1mb of virtual address space for its
stack. So straight off the bat you've wasted 500mb of addres space
(out of a total of only 2gb).

Moreover, their stacks will be scattered over memory, so each context
switch will mean that the cache is useless, so you'll get very bad
cache performance.

Finally, my memory is that each call to CreateThread involves
inter-process communication with one of the windows DLLs (smss?) and
it does this so the OS can keep a track of all threads and tidy them
up when a process terminates. IPC is always slowish.

If your hardware has N cores, then you will always lose performance if
you have more than N active threads.

The only reason to have lots of threads is because it makes your
program logic easier, and because you want your code to run on future
manycore machines without recompilation. Does 500 threads really make
your code easier to design, understand and debug? it's hard to
believe...
--
Lucian
Dec 17 '06 #9
Mark R. Dawson <Ma*********@di scussions.micro soft.comwrote:
>Lucian wrote:
>The only reason to have lots of threads is because it makes your
program logic easier, and because you want your code to run on future
manycore machines without recompilation
That is not the reason to be using threads,
basicially using a number of threads is useful even on a single core
machine because they improve throughput of your program
Sure, what you listed are good reasons to use threads -- I was just
talking about the reasons for using LOTS of threads.

--
Lucian
Dec 17 '06 #10

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

Similar topics

0
1688
by: Rob | last post by:
Hi, do you know any any Java implementation of an improved read-write lock that can give three kind of locks: - Read - Write - Promotable Read The read and write locks are as usual. The promotable read lock can be used when you have to do a lot of
14
2790
by: Antoon Pardon | last post by:
The queue and condition class allow threads to wait only a limited time. However this currently is implemented by a polling loop. Now for those who like to avoid polling I have here a Tlock class that allows for a timeout but doesn't use polling. All comments are welcome. ----------------------- Tlock.py -------------------------------
4
40249
by: francis70 | last post by:
Hi, I have these 2 problem? Is there a way in Oracle to read UNCOMMITED data. i.e. in Oracle the normal behaviour is that a user's updates to a table are visible to other users ONLY when the user commits. But in Informix there is this thing called ISOLATION LEVELS. For example by setting the ISOLATION LEVEL to DIRTY READ, a user will read dirty data, i.e. the last uncommited updated value of a field by some other user. Is
1
3137
by: Abe | last post by:
Need some information regarding SQL Server locking. Requirement is to run SQL Statements for reports (read-only) that will not lock-out other people trying to update (write lock). For this, we tried the following to make the db connection not deny write locks (our report code will not have a read-only lock). ADODB.ConnectionObj.Mode =adModeShareDenyNone But this made our connection bumped whenever someone tried to update.
18
4876
by: jas | last post by:
Hi, I would like to start a new process and be able to read/write from/to it. I have tried things like... import subprocess as sp p = sp.Popen("cmd.exe", stdout=sp.PIPE) p.stdin.write("hostname\n") however, it doesn't seem to work. I think the cmd.exe is catching it.
0
3163
by: Andrew Dowding | last post by:
Hi Everybody, I have been looking at problems with my Windows Forms C# application and it's little Jet 4 (Access) database for the last few days. The Windows Forms app implements a facade and implementation, data abstraction layer. But because each data adapter in the implementation layer has a connection object that opens and closes as needed, I found I got several errors from the Jet engine when there were simultaneous connections to...
4
2181
by: akhare1 | last post by:
OK, before I start, let me clarify a few things here. This is not the run of the mill failure to read a registry key while trying to write to the Event Log. Here's our setup: a) IIS 6.0 server w/ SharePoint installed b) ASP.NET application w/ NTLM authentication running under an account (application pool) with ADMIN privileges on the local box. c) We are NOT using impersonation
6
3581
by: Casey Bralla | last post by:
I'd like to read ASCII data from a serial port, but (once again) I'm having trouble getting started. (Can't seem to find the basic level of docs to get going <sigh>) I'd like to use only standard "built-in" modules if possible. Could somebody offer a simple code-snippet to get me started reading from a serial port? Thanks!
3
2961
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 for Item (this)? Normally,do I need sync at all? Isn't that true without sync the program can run faster?
0
8397
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
8310
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,...
1
8503
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8605
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...
1
6167
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5632
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();...
1
2731
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1957
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1620
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.