0

Hello friends have a doubt in threaded application.

    class sample
    {
        static volatile bool _shutdownThreads;
        static readonly object _lockerObject = new object();

    main()
    {    
       create thread for samplemethod()

       lock(_lockerObject)
       {
           _shutdownThreads = true;
       }
    }

    samplemethod()
    {
       while(true)
       {
          lock(_lockerObject)
          {
             if(_shutdownThreads) break;
          }
        }
    }
    }

(1)ok i guess you might have understood what i am trying to accomplish. I need to have a safe way to use the _shutdownThreads variable. is this the right approach?

(2)if i lock a block of code all the variables inside the block gets locked too? i mean even other threads(for example main) cant access the variable. am i right?

Michael
  • 3,982
  • 4
  • 30
  • 46
wenn32
  • 1,256
  • 2
  • 17
  • 26

2 Answers2

0

Yes, you are right. The purpose of lock is to let one thread access a code block while other threads will wait. However in your specific case: it does not make sense to lock a boolean assignment. This will be atomic anyway.

Community
  • 1
  • 1
Krumelur
  • 32,180
  • 27
  • 124
  • 263
0

"I need to have a safe way to use the _shutdownThreads variable. is this the right approach?"

Yes, and no. It's safe, but you have a busy loop that will use A LOT of CPU for no good reason. There are better options for waiting for an event, but you can at least make it a lot less horrific by making the thread sleep a while between each check:

while(true) {
  lock(_lockerObject) {
    if(_shutdownThreads) break;
  }
  Thread.Sleep(100);
}

"if i lock a block of code all the variables inside the block gets locked too?"

No, not at all. The lock doesn't keep any other thread from accessing any data what so ever. The only thing that the lock does is keeping any other thread from entering a code block that uses the same identifier reference (_lockerObject in your case).

To protect the data, you have to use locks around every code block that accesses the data, using the same identifier reference.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • oh ok so as per my understanding a variable will not be accessed for read at the same time? am i right? – wenn32 Jan 05 '14 at 18:48
  • @wenn32: If you have all code that accesses the variable inside locks, then only one thread can run that code at any time. The variable itself isn't protected in any way though, so if you have any code outside locks that accesses it, the locks won't protect it. – Guffa Jan 05 '14 at 19:17