in reply to Re^8: multithreads newbie question
in thread multithreads newbie question

Why do I have to lock the object every time I use it? If I know that sub1 only changes $self->{KEY1} and sub2 only changes $self->{KEY2}, and both do not depend on the keys the other changes, do I still have to lock the object?

Can you please elaborate just a bit on what you wrote on the last line?

Replies are listed 'Best First'.
Re^10: multithreads newbie question
by roboticus (Chancellor) on Aug 11, 2010 at 10:34 UTC

    daverave:

    In general, you can avoid locking if you can guarantee that there would be no overlap. However, I'd argue against it:

    • First, it's difficult to make those sorts of guarantees, especially as the constraints get more complicated.
    • Second, during maintenance, it's amazingly simple to break the guarantee.

    The second reason is especially pernicious, as thread interaction bugs can raise their heads infrequently. The interval between creating the bug and being bitten by it can hide the cause of the bug, as you wouldn't necessarily remember the change you made four months ago!

    ...roboticus

Re^10: multithreads newbie question
by ikegami (Patriarch) on Aug 11, 2010 at 15:55 UTC

    Practical usage patterns are never that simple. Even when they are that simple, you have to approach them as if they're not to catch possible race conditions. If the work is divided in discrete, isolated work units, you don't have to worry about that. If we knew more about what you were doing, we might be ale to provide better solutions.