How to lock other threads

J

jeff.ranney

Hi all.

I wrote this C# code:

lock(this)
{

/ /write to a file

}



thinking that it was going to make other threads wait in line to access
the same block of code. But as I now understand it this only locks the
current thread.

Does anyone know if there a way to do what I was originally intending?
- stop other threads from simultaneously accessing the code inside a
given block?

Thanks,

Jeff
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

|
| Hi all.
|
| I wrote this C# code:
|
| lock(this)
| {
|
| / /write to a file
|
| }
|
|
|
| thinking that it was going to make other threads wait in line to access
| the same block of code. But as I now understand it this only locks the
| current thread.

What make you think that?
As long as the other threads lock on the same instance only one thread will
have access to writing the file.
 
S

Stoitcho Goutsev \(100\)

This is not true. And if you think about it it deosn't make any sense. Any
thread that tries to execute the lock will block if the object has been
locked already by another thread. If a thread makes an attempt to lock an
object that it already lock it just goes through the lock - no thread can
lock itself.

Locking is a technique for interthread synchronization, thus what you said
cannot be true.
 
R

Robson Siqueira

Jeff,

Why don't you create a member which you can use to lock? You could use
Interlocked class, ReadWriterLock class, Monitor class, etc, to manipulate
this object. Even using just lock would work.

Best,
 
J

jeff.ranney

Thanks to everyone for your helpful info.

You guys are right that my statement 'only locks the current thread'
makes no sense. I was going to add that as part of my question.. the
fact that i didn't understand even the meaning of that. 'locking'
*means* locking for other threads..., you are right.

Someone at work told me this. But thinking about it what I think she
told me was that this lock statement was in an object that was not a
Singleton.. different threads were making their own instance of of
this object, and that therefore the lock was basically doing nothing.
Because it would only block other threads attempting to get inside that
code from the same instance of that object in which the lock statement
resides.

Is she right and if so, how can I lock the other threads?

Thanks again!!

Jeff
 
S

Stoitcho Goutsev \(100\)

Jeff,

She is right that if you want the lock to work all the thread should lock on
the same instance of the object. Otherwise each thread will acquire lock on
different objects thus there won't be any interthread locking and the code
will run as there is no lock at all.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top