[Threading] Why doesn't this work?

C

Cool Guy

In the following, why isn't there a pause when trying to access c in the
statement "Console.WriteLine(c.i);"?

I thought that c would be locked and therefore not accessible at the time.
Why isn't this the case?



using System;
using System.Threading;

class C
{
public int i = 0;

static void Main()
{
C c = new C();

Thread thread = new Thread(new ThreadStart(c.Foo));
thread.Start();

for (int i = 0; i < 10; i++)
{
Console.WriteLine(c.i);
}

Console.Read();
}

void Foo()
{
lock (this)
{
Thread.Sleep(10000);
i++;
}
}
}
 
C

Cool Guy

Jon said:
Locks are effectively co-operative - locking something doesn't actually
stop anyone else from accessing it; it stops another thread from
acquiring the same lock.

Oh, this was the source of my confusion. I presumed it locked all other
access to the variable.

Thanks for the replies.
 
R

Robert Jordan

Hi "Cool Guy"
In the following, why isn't there a pause when trying to access c in the
statement "Console.WriteLine(c.i);"?

I thought that c would be locked and therefore not accessible at the time.
Why isn't this the case?

comments inline
using System;
using System.Threading;

class C
{
public int i = 0;

static void Main()
{
C c = new C();

Thread thread = new Thread(new ThreadStart(c.Foo));
thread.Start();

for (int i = 0; i < 10; i++)
{ lock (this) {
Console.WriteLine(c.i); }
}

Console.Read();
}

void Foo()
{
lock (this)
{
Thread.Sleep(10000);
i++;
}
// the thread ends here. are you aware of that?

bye
Rob
 
J

Jon Skeet [C# MVP]

Cool Guy said:
In the following, why isn't there a pause when trying to access c in the
statement "Console.WriteLine(c.i);"?

I thought that c would be locked and therefore not accessible at the time.
Why isn't this the case?

Locks are effectively co-operative - locking something doesn't actually
stop anyone else from accessing it; it stops another thread from
acquiring the same lock.
 

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