[Threading] Why doesn't this work?

  • Thread starter Thread starter Cool Guy
  • Start date Start date
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++;
}
}
}
 
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.
 
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
 
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.
 
Back
Top