Threading newbie: Lock statement

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Hi Group,

Does the "lock" statement lock the "ressource" or the code section (like a
critical section)?

Let me elaborate: I have two threads accessing the same ressource, but from
*different* parts of the code. Can I use the lock statement to synchronise
access, or can I only use lock when the threads access the ressource from
the *same* part of he code (critical section). MSDN is somewhat unclear
about this.

The following simplified code sample illustrates the problem:

// Imagine I have Thread1 executing only MyFirstThreadProcedure() a 1000
times.
// At the same time I have Thread2 executing on MySecondThreadProcedure() a
1000 times.
class Class1 {
static int counter;
public static void MyFirstThreadProcedure()
{
lock (counter) { counter++; }
}
public static void MySecondThreadProcedure()
{
lock (counter) { counter += 2; }
}
}

The code sample above works, but I have only tried this on a uniprocessor
machine.

(Let me know if I have formulated my question in an unclear way)

Kind Regards
Jan


.



Relevant Pages

  • Re: Threading newbie: Lock statement
    ... Can I use the lock statement to ... // At the same time I have Thread2 executing on MySecondThreadProcedure() ... public static void MySecondThreadProcedure() ... An integer is not a reference type, so you will be locking on a boxed copy ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Threading newbie: Lock statement
    ... Let me elaborate: I have two threads accessing the same ressource, but from *different* parts of the code. ... Can I use the lock statement to synchronise access, or can I only use lock when the threads access the ressource from the *same* part of he code. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Threading newbie: Lock statement
    ... Let me elaborate: I have two threads accessing the same ressource, ... Can I use the lock statement to ... synchronise access, or can I only use lock when the threads access the ... ressource from the *same* part of he code. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: problem with pthread_mutex_timedlock
    ... and if the lock was not free, it returns the error code 110, but I have ... function expects an *absolute time* for the timeout, ... // try to lock the ressource again. ...
    (comp.os.linux.development.apps)
  • Re: Threading newbie: Lock statement
    ... having a value type as the lock expression will cause a compilation error. ... public static void MySecondThreadProcedure() ... An integer is not a reference type, so you will be locking on a boxed ...
    (microsoft.public.dotnet.languages.csharp)