To lock or not?

  • Thread starter Thread starter fritzcwdev
  • Start date Start date
F

fritzcwdev

I have a class as follows:

public class OperationFeedback
{
DateTime _startTime;

public DateTime StartTime
{
get
{
return _startTime;
}
set
{
_startTime = value;
}
}

}

Set will occur in a background thread. Getting will occur from my GUI
thread. Should I implement a lock inside the get and set? If I so why?

Thanks,

- Fritz
 
Fritz,

If the StartTime property is the only one item that you need to
synchronize, then I would say in the class is fine. However, as a general
guideline, I think that there are few classes that should do this (even this
one). The reason for this is that operations are usually more complex than
simple get/sets, and you really should be wrapping those entire operations
in lock blocks to make sure that the whole operation is synchronized, not
just one part of it.

Of course, if you encapsulate your operations well enough, you can
synchronize access to those in a class.
 
If I leave the class as is? Is it possible that when the "get" is
called from one thread in the middle of the "set" from another, that
the value could contain part of the old and part of the new value
(since DateTime is not atomic). If I want to ensure a proper value
when I "get", I suspect I need to lock (this is what I am trying to
confirm / understand).

- Fritz
 
Fritz,

Yes, that is the case, but the rest of my post spoke about how if you
don't perform locking in the class, then it should be performed on a higher
level, as usualy, it's not just one operation that you have to synchronize.

For example, if later, you have other pieces of data that you have to
synchronize access to, then you will have to wrap all the changes up in a
synchronization block (lock block). If all of the properties/methods have
their own synchronization and you don't wrap it all in a lock block, then
you have to make sure that the code that accesses those methods/properties
always does it in the same order.

Doing it on that granular a level actually increases your chances of
deadlock, assuming you are mixing it with other methods/properties that lock
on that granular a level.
 
the value could contain part of the old and part of the new value

So are you saying that you are worried about having a stored value of say
"3/3/2003 3:33 PM" and then having the set method called to set a new value
of say "5/5/2005 5:55 AM" and during this process call the get method and
end up reading something like "5/5/2005 3:33 PM" (contain part of the old
and part of the new value)?

Did I totally misunderstand your question? :)
 
So are you saying that you are worried about having a stored value of say
"3/3/2003 3:33 PM" and then having the set method called to set a new value
of say "5/5/2005 5:55 AM" and during this process call the get method and
end up reading something like "5/5/2005 3:33 PM" (contain part of the old
and part of the new value)?

Did I totally misunderstand your question? :)

No, that is my concern. Although I'm not sure it would manifest itself
exactly like that (this would depend on the internal implementation
DateTime).

- Fritz
 
No, that is my concern. Although I'm not sure it would manifest itself
exactly like that (this would depend on the internal implementation
DateTime).

- Fritz

DateTime is a 64 bit structure. If you look at the MSDN entry there is
an explicit warning that it is not thread safe on certain
architectures as threads could switch before it is completely commited.
 
Fritz said:
No, that is my concern. Although I'm not sure it would manifest itself
exactly like that (this would depend on the internal implementation
DateTime).

- Fritz

Yes, it looks like that could potentially happen (on 32-bit Windows). The
DateTime type stores its value internally as a UInt64. According to
http://msdn2.microsoft.com/en-us/library/ms684122.aspx, read and writes of
64 bit values are not guaranteed to be atomic on 32-bit Windows, so
potentially the writing thread might only get time to write half of the
bytes before it gets interupted by the reading thread.

I have no idea how common this problem is or if it even exists in practice.
The article only make a general statement regarding 32-bit Windows. The
behavoiur might very well be that it's an atomic operation on XP and Vista,
but not on 2000 for example (note: I'm only guessing here).

For the record, I've never seen it happen (fwiw :-)).

/claes
 
Doing it on that granular a level actually increases your chances of
deadlock, assuming you are mixing it with other methods/properties that
lock on that granular a level.

Why is that though? I would have locking get/set of each property would be
better as long as the property is doing nothing but returning some state.

Also, in this case I would guess a reader/writer lock would work fine as
well.
 
Why is that though? I would have locking get/set of each property would
be better as long as the property is doing nothing but returning some
state.

Consider first that deadlocking code is buggy code. So the real question
is, why would locking at a finer level of granularity lead to more bugs?

The answer is simply that of opportunity. If you have only one lock,
there's no chance for deadlock at all. If you have two locks, there's
some chance for deadlock but it's not too hard to design around that
possibility. If you have fifty locks, then you've got some huge number of
permutations that could lead to deadlock. Make a single mistake and BOOM!

Pete
 
Peter Duniho said:
Consider first that deadlocking code is buggy code. So the real question
is, why would locking at a finer level of granularity lead to more bugs?

The answer is simply that of opportunity. If you have only one lock,
there's no chance for deadlock at all. If you have two locks, there's
some chance for deadlock but it's not too hard to design around that
possibility. If you have fifty locks, then you've got some huge number of
permutations that could lead to deadlock. Make a single mistake and BOOM!


I didnt say that we have multiple lock objects. You can use the same object.
In this case, all getter can acquire a readonlylock. For setters, I would
use the same object on which you apply the lock. Why is that hmm... bad?

I am curious to know because we follow this pattern and have had no issues
at all. I would like to know the downside that we are missing.
 
I didnt say that we have multiple lock objects. You can use the same
object. In this case, all getter can acquire a readonlylock. For
setters, I would use the same object on which you apply the lock. Why is
that hmm... bad?

Well, not having multiple lock objects but then locking at such a low
level is also bad, but for performance reasons.

It really just depends. Without knowing everything that's going on with
the code, it's hard to say. Sometimes a fine-granularity on your locking
code is no problem. But as Nicholas says, often times you've got a
situation where at that level of granularity you're just going to keep
acquiring the same lock over and over. You're better off in that
situation to just grab the lock once, do everything you need to do, and
then release it.
I am curious to know because we follow this pattern and have had no
issues at all. I would like to know the downside that we are missing.

If you understand the _potential_ for problems and can ensure they are not
an issue here, you should be okay. If all you are ever locking is that
one DateTime property, it's not an issue.

That said, if all you're ever locking is that one DateTime property then
you may not need the lock at all. You can use boxing instead to create an
atomic access:

object _startTime = new DateTime();

public DateTime StartTime
{
get { return (DateTime)_startTime; }
set { _startTime = value; }
}

I did a quick test (code below) and two threads executing 10 million
iterations accessing both the setter and getter of the property are
consistently 30-40% faster using boxing than using a lock. Of course,
even the "slow" case took only 1.1 seconds to do 10 million iterations.
The usual caveat of "most code is going to spend most of its time doing
more interesting things" applies, meaning that even if you could get the
overhead down to zero it might not make a real difference in your
application's performance.

On the other hand, if you are entering and leaving a lock for every little
thing, that might cause that caveat to no longer be applicable. All of
the sudden, performance matters. :)

Pete



using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace TestLockPerformance
{
class Program
{
public interface IDateTimeHolder
{
DateTime DateTime
{
get;
set;
}
}

public class LockingHolder : IDateTimeHolder
{
#region IDateTimeHolder Members

private DateTime _dt;
private object _objLock = new object();

public DateTime DateTime
{
get
{
lock (_objLock)
{
return _dt;
}
}
set
{
lock (_objLock)
{
_dt = value;
}
}
}

#endregion
}

public class BoxingHolder : IDateTimeHolder
{
#region IDateTimeHolder Members

private volatile object _dt = new DateTime();

public DateTime DateTime
{
get
{
return (DateTime)_dt;
}
set
{
_dt = value;
}
}

#endregion
}

public class HolderThread
{
private IDateTimeHolder _dth;
private int _iterations;
private Thread _thread;

public HolderThread(IDateTimeHolder dth, int iterations)
{
_dth = dth;
_iterations = iterations;
_thread = new Thread(_ThreadStart);
}

public void Start()
{
_thread.Start();
}

public void Wait()
{
_thread.Join();
}

private void _ThreadStart()
{
while (_iterations-- > 0)
{
DateTime dtT = _dth.DateTime;

_dth.DateTime = dtT;
}
}
}

static void Main(string[] args)
{
int iterations = 10000000;

switch (args.Length)
{
case 2:
{
int iT;

if (int.TryParse(args[1], out iT))
{
iterations = iT;
}
}
goto case 1;
case 1:
{
IDateTimeHolder dth;

switch (args[0])
{
case "lock":
dth = new LockingHolder();
break;
case "box":
dth = new BoxingHolder();
break;
default:
Console.WriteLine("first parameter mustbe
\"lock\" or \"box\"");
dth = null;
break;
}

if (dth != null)
{
HolderThread ht1 = new HolderThread(dth,
iterations),
ht2 = new HolderThread(dth, iterations);

Stopwatch sw = new Stopwatch();
sw.Start();
ht1.Start();
ht2.Start();
ht1.Wait();
ht2.Wait();
sw.Stop();

Console.WriteLine("{0} iterations took {1}",
iterations, sw.Elapsed);
}
}
break;
default:
Console.WriteLine("usage: {0} lock|box [<iteration
count>]", Environment.CommandLine.Split(' ')[0]);
break;
}
}
}
}
 
Thanks Pete. It was helpful. I didnt know about Boxing making it atomic.

---
Ajay

I didnt say that we have multiple lock objects. You can use the same
object. In this case, all getter can acquire a readonlylock. For setters,
I would use the same object on which you apply the lock. Why is that
hmm... bad?

Well, not having multiple lock objects but then locking at such a low
level is also bad, but for performance reasons.

It really just depends. Without knowing everything that's going on with
the code, it's hard to say. Sometimes a fine-granularity on your locking
code is no problem. But as Nicholas says, often times you've got a
situation where at that level of granularity you're just going to keep
acquiring the same lock over and over. You're better off in that
situation to just grab the lock once, do everything you need to do, and
then release it.
I am curious to know because we follow this pattern and have had no
issues at all. I would like to know the downside that we are missing.

If you understand the _potential_ for problems and can ensure they are not
an issue here, you should be okay. If all you are ever locking is that
one DateTime property, it's not an issue.

That said, if all you're ever locking is that one DateTime property then
you may not need the lock at all. You can use boxing instead to create an
atomic access:

object _startTime = new DateTime();

public DateTime StartTime
{
get { return (DateTime)_startTime; }
set { _startTime = value; }
}

I did a quick test (code below) and two threads executing 10 million
iterations accessing both the setter and getter of the property are
consistently 30-40% faster using boxing than using a lock. Of course,
even the "slow" case took only 1.1 seconds to do 10 million iterations.
The usual caveat of "most code is going to spend most of its time doing
more interesting things" applies, meaning that even if you could get the
overhead down to zero it might not make a real difference in your
application's performance.

On the other hand, if you are entering and leaving a lock for every little
thing, that might cause that caveat to no longer be applicable. All of
the sudden, performance matters. :)

Pete



using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Diagnostics;

namespace TestLockPerformance
{
class Program
{
public interface IDateTimeHolder
{
DateTime DateTime
{
get;
set;
}
}

public class LockingHolder : IDateTimeHolder
{
#region IDateTimeHolder Members

private DateTime _dt;
private object _objLock = new object();

public DateTime DateTime
{
get
{
lock (_objLock)
{
return _dt;
}
}
set
{
lock (_objLock)
{
_dt = value;
}
}
}

#endregion
}

public class BoxingHolder : IDateTimeHolder
{
#region IDateTimeHolder Members

private volatile object _dt = new DateTime();

public DateTime DateTime
{
get
{
return (DateTime)_dt;
}
set
{
_dt = value;
}
}

#endregion
}

public class HolderThread
{
private IDateTimeHolder _dth;
private int _iterations;
private Thread _thread;

public HolderThread(IDateTimeHolder dth, int iterations)
{
_dth = dth;
_iterations = iterations;
_thread = new Thread(_ThreadStart);
}

public void Start()
{
_thread.Start();
}

public void Wait()
{
_thread.Join();
}

private void _ThreadStart()
{
while (_iterations-- > 0)
{
DateTime dtT = _dth.DateTime;

_dth.DateTime = dtT;
}
}
}

static void Main(string[] args)
{
int iterations = 10000000;

switch (args.Length)
{
case 2:
{
int iT;

if (int.TryParse(args[1], out iT))
{
iterations = iT;
}
}
goto case 1;
case 1:
{
IDateTimeHolder dth;

switch (args[0])
{
case "lock":
dth = new LockingHolder();
break;
case "box":
dth = new BoxingHolder();
break;
default:
Console.WriteLine("first parameter must be
\"lock\" or \"box\"");
dth = null;
break;
}

if (dth != null)
{
HolderThread ht1 = new HolderThread(dth,
iterations),
ht2 = new HolderThread(dth, iterations);

Stopwatch sw = new Stopwatch();
sw.Start();
ht1.Start();
ht2.Start();
ht1.Wait();
ht2.Wait();
sw.Stop();

Console.WriteLine("{0} iterations took {1}",
iterations, sw.Elapsed);
}
}
break;
default:
Console.WriteLine("usage: {0} lock|box [<iteration
count>]", Environment.CommandLine.Split(' ')[0]);
break;
}
}
}
}
 

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