Why does threading lock in different classes?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • oystgoymp
    New Member
    • Feb 2007
    • 2

    #1

    Why does threading lock in different classes?

    Ok first I must preface this question with a disclaimer, I'm really new to threading so this may be a 'newbie' question but I searched google and couldn't find an answer. As I understand it a critical section is code that can only be accessed by one thread, the danger being one thread will overwrite a value before the other is finished and vice versa. What can you do about changes made outside of your class for example, I have a line monitoring program:

    Code:
    int currentNumber = provider.GetCurrentNumber();
    if(provider.CanPassNumber(false, currentNumber))
    {
    currentNumber+=2;
    provider.SetNumber(currentNumber);
    }
    and on another thread I have something like this:

    Code:
    if(condition)
        provider.SetNumber(numberToSet);
    Now I'm afraid that in the first function I get currentNumber which is 5, right after that on another thread the number is set to 7 and then it rewrites the 7 to 6, ignoring the change made by the thread that set it to 7.

    Is there anyway to lock provider.SetNum ber until the first function finishes? The critical section is basically the currentNumber which can be changed by many places in the program.

    I hope I made myself clear, if not let me know and I will try to explain myself better.

    Also I made the functions really short for the example. In reality the function is much longer and makes changes to currentNumber many times so I don't really want to put a lock around the entire function. If I lock every call to provider.SetNum ber and release it after I finish it can change during the time it is released before I lock it again to call provider.SetNum ber. Honestly I'm also worried about locking the entire function because of performance and deadlock.
  • bentleyw
    New Member
    • Feb 2008
    • 32

    #2
    One common way to handle this type of situation would be to create a synchronizing variable and use the lock construct to hold until it's free. Here's a nice example of how to do this:

    Comment

    • Aimee Bailey
      Recognized Expert New Member
      • Apr 2010
      • 197

      #3
      Im sure this maybe seen as ugly, but you could try...

      Code:
      private bool locked = false;
      private string _LockableValue = "";
      
      public string LockableValue 
      {
          set {
              if (!locked) {
                  locked = true; 
                  _LockableValue = value;
                  locked = false;
              }
          }
          get { return _LockableValue; }
      }
      lol.

      Comment

      Working...