does reading op need semaphore in multi-thread coding?

  • Thread starter Thread starter fred
  • Start date Start date
F

fred

hi All,
I am working in a multi thread project. is it necessary to use
semaphore when doing reading operation. in my case I do loop to read
share memory data. I remember it should be fine to read without
protection.
Thank in advance.
Fred
 
fred said:
I am working in a multi thread project. is it necessary to use
semaphore when doing reading operation. in my case I do loop to read
share memory data. I remember it should be fine to read without
protection.

No, it isn't. Depending on exactly what you're doing, the JIT or CPU
may decide to cache the results of an earlier read, not refreshing it
each iteration.

Either store your data in volatile variables, or only touch it inside a
lock, using the same lock to protect both the read and the write of the
data.
 
fred said:
hi All,
I am working in a multi thread project. is it necessary to use
semaphore when doing reading operation. in my case I do loop to read
share memory data. I remember it should be fine to read without
protection.
Thank in advance.
Fred

Each single read is atomic, and is guaranteed not to give you a halfway
changed value, as long as it's a native data type.

If you are looping a list or collection that may change in size, though,
that needs to be synchronised.
 
Göran Andersson said:
Each single read is atomic, and is guaranteed not to give you a halfway
changed value, as long as it's a native data type.

No - unless you deem "double" and "long" not to be native data types.
If you are looping a list or collection that may change in size, though,
that needs to be synchronised.

There's more to worry about than atomicity - there's volatility too.
Suppose the value of an int variable changes from 0 to 5. Without any
extra work, I know that I'll never see any value *other* than 0 or 5
(due to atomicity) but there's no guarantee that I'll *ever* see 5.
That's not good for most scenarios :)
 
Jon said:
No - unless you deem "double" and "long" not to be native data types.

Right. "Native" wasn't exactly what I was after.
There's more to worry about than atomicity - there's volatility too.
Suppose the value of an int variable changes from 0 to 5. Without any
extra work, I know that I'll never see any value *other* than 0 or 5
(due to atomicity) but there's no guarantee that I'll *ever* see 5.
That's not good for most scenarios :)

Good point.
 

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

Back
Top