Threading newbie: Lock statement
- From: "Jan" <jan_dynnesen@xxxxxxxxxxx>
- Date: Mon, 6 Nov 2006 02:29:03 +0100
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
.
- Follow-Ups:
- Re: Threading newbie: Lock statement
- From: Göran Andersson
- Re: Threading newbie: Lock statement
- From: Arne Vajhøj
- Re: Threading newbie: Lock statement
- Prev by Date: Re: Hashtable question
- Next by Date: Re: REALLY need help with SendMessage WM_GETCONTROLNAME
- Previous by thread: Hashtable question
- Next by thread: Re: Threading newbie: Lock statement
- Index(es):
Relevant Pages
|