a threading test for your use/thoughts on affinity

N

not_a_commie

Here's some code I wrote trying to track down a deadlock bug. I was
unable to make this code deadlock on my Core 2 Duo. I'd be interested,
though, if y'all think it is the right way to use thread affinity or
not. I'd also be interested if you saw any code that might cause a
deadlock in some other scenario.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TestThreading
{
public sealed class Program
{
static private Thread _backgroundThread = null;
static private EventWaitHandle _tickCountUpdateRequest = new
EventWaitHandle(false, EventResetMode.AutoReset);
static private EventWaitHandle _tickCountUpdateDone = new
EventWaitHandle(false, EventResetMode.AutoReset);
static public long CurrentTickCount = 0;
private static void _BackgroundThreadFunc()
{
Thread.BeginThreadAffinity(); // always read the tick count from
the same CPU -- not necessary in Vista
while (true)
{
_tickCountUpdateRequest.WaitOne();
CurrentTickCount = System.Diagnostics.Stopwatch.GetTimestamp();
_tickCountUpdateDone.Set();
}
Thread.EndThreadAffinity(); // never called; but here for symmetry
}

static Program() {
_backgroundThread = new Thread(new
ThreadStart(_BackgroundThreadFunc));
_backgroundThread.IsBackground = true;
_backgroundThread.Start();
}

public long GetCount()
{
lock (_backgroundThread)
{
Program._tickCountUpdateRequest.Set();
Program._tickCountUpdateDone.WaitOne();
return CurrentTickCount;
}
}

private static void _GetCountFunc() {
Random r = new Random();
Program p = new Program();
while (true)
{
// sleep a random amount of time then read
Thread.Sleep(r.Next(20));
lock (System.Console.Out)
{
System.Console.Out.WriteLine("thread " +
Thread.CurrentThread.ManagedThreadId +
": " + p.GetCount().ToString());
}
}
}

static void Main(string[] args)
{
Random r = new Random();
Thread d = new Thread(new ThreadStart(_GetCountFunc));
d.Start();
while (true)
{
Thread a = new Thread(new ThreadStart(_GetCountFunc));
Thread b = new Thread(new ThreadStart(_GetCountFunc));
Thread c = new Thread(new ThreadStart(_GetCountFunc));
a.Start();
b.Start();
c.Start();
Thread.Sleep(r.Next(50));
a.Abort();
Thread.Sleep(r.Next(50));
b.Abort();
c.Abort();
}
}
}
}
 
C

Chris Mullins [MVP]

I have to confess, I'm completly missing what you're trying to accomplish
here.

Why are you trying to accomplish with Begin/EndThreadAffinity? All this does
is tell the CLR you have affinity for the actualy thread you're scheduled
on.

You really are trying to set PROCESSOR affinity, not Thread Affinity.
Unfortunatly, you're not doing what you think - the O/S Thread Scheduler may
still schedule your thread on either of the Cores on your system.

Duffy has a recent blog entry where he's using processor affinity for some
tricks - you can just copy what he does...
http://www.bluebytesoftware.com/blog/PermaLink,guid,4358c4bb-0326-48e9-a8ef-df69a3980e6d.aspx

As for deadlocks - yes, your code is susceptable to them. You're aborting
threads that may be inside a lock at the time of the abort. This is a very
bad practice...

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins

not_a_commie said:
Here's some code I wrote trying to track down a deadlock bug. I was
unable to make this code deadlock on my Core 2 Duo. I'd be interested,
though, if y'all think it is the right way to use thread affinity or
not. I'd also be interested if you saw any code that might cause a
deadlock in some other scenario.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TestThreading
{
public sealed class Program
{
static private Thread _backgroundThread = null;
static private EventWaitHandle _tickCountUpdateRequest = new
EventWaitHandle(false, EventResetMode.AutoReset);
static private EventWaitHandle _tickCountUpdateDone = new
EventWaitHandle(false, EventResetMode.AutoReset);
static public long CurrentTickCount = 0;
private static void _BackgroundThreadFunc()
{
Thread.BeginThreadAffinity(); // always read the tick count from
the same CPU -- not necessary in Vista
while (true)
{
_tickCountUpdateRequest.WaitOne();
CurrentTickCount = System.Diagnostics.Stopwatch.GetTimestamp();
_tickCountUpdateDone.Set();
}
Thread.EndThreadAffinity(); // never called; but here for symmetry
}

static Program() {
_backgroundThread = new Thread(new
ThreadStart(_BackgroundThreadFunc));
_backgroundThread.IsBackground = true;
_backgroundThread.Start();
}

public long GetCount()
{
lock (_backgroundThread)
{
Program._tickCountUpdateRequest.Set();
Program._tickCountUpdateDone.WaitOne();
return CurrentTickCount;
}
}

private static void _GetCountFunc() {
Random r = new Random();
Program p = new Program();
while (true)
{
// sleep a random amount of time then read
Thread.Sleep(r.Next(20));
lock (System.Console.Out)
{
System.Console.Out.WriteLine("thread " +
Thread.CurrentThread.ManagedThreadId +
": " + p.GetCount().ToString());
}
}
}

static void Main(string[] args)
{
Random r = new Random();
Thread d = new Thread(new ThreadStart(_GetCountFunc));
d.Start();
while (true)
{
Thread a = new Thread(new ThreadStart(_GetCountFunc));
Thread b = new Thread(new ThreadStart(_GetCountFunc));
Thread c = new Thread(new ThreadStart(_GetCountFunc));
a.Start();
b.Start();
c.Start();
Thread.Sleep(r.Next(50));
a.Abort();
Thread.Sleep(r.Next(50));
b.Abort();
c.Abort();
}
}
}
}
 
C

Chris Mullins [MVP]

I really need to edit my posts before sending them out. I've got duplicate
sentences and everything in there. Sorry about that...

The conclusion is the same though - you're not setting processor affinity
(which is what you're trying to accomplish), but are rather setting affinity
of the Managed Thread to the O/S thread.

This means your thread can still be scheduled on either processing core,
depending on the circumstances.

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins

Chris Mullins said:
I have to confess, I'm completly missing what you're trying to accomplish
here.

Why are you trying to accomplish with Begin/EndThreadAffinity? All this
does is tell the CLR you have affinity for the actualy thread you're
scheduled on.

You really are trying to set PROCESSOR affinity, not Thread Affinity.
Unfortunatly, you're not doing what you think - the O/S Thread Scheduler
may still schedule your thread on either of the Cores on your system.

Duffy has a recent blog entry where he's using processor affinity for some
tricks - you can just copy what he does...
http://www.bluebytesoftware.com/blog/PermaLink,guid,4358c4bb-0326-48e9-a8ef-df69a3980e6d.aspx

As for deadlocks - yes, your code is susceptable to them. You're aborting
threads that may be inside a lock at the time of the abort. This is a very
bad practice...

--
Chris Mullins, MCSD.NET, MCPD:Enterprise, Microsoft C# MVP
http://www.coversant.com/blogs/cmullins

not_a_commie said:
Here's some code I wrote trying to track down a deadlock bug. I was
unable to make this code deadlock on my Core 2 Duo. I'd be interested,
though, if y'all think it is the right way to use thread affinity or
not. I'd also be interested if you saw any code that might cause a
deadlock in some other scenario.

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TestThreading
{
public sealed class Program
{
static private Thread _backgroundThread = null;
static private EventWaitHandle _tickCountUpdateRequest = new
EventWaitHandle(false, EventResetMode.AutoReset);
static private EventWaitHandle _tickCountUpdateDone = new
EventWaitHandle(false, EventResetMode.AutoReset);
static public long CurrentTickCount = 0;
private static void _BackgroundThreadFunc()
{
Thread.BeginThreadAffinity(); // always read the tick count from
the same CPU -- not necessary in Vista
while (true)
{
_tickCountUpdateRequest.WaitOne();
CurrentTickCount = System.Diagnostics.Stopwatch.GetTimestamp();
_tickCountUpdateDone.Set();
}
Thread.EndThreadAffinity(); // never called; but here for symmetry
}

static Program() {
_backgroundThread = new Thread(new
ThreadStart(_BackgroundThreadFunc));
_backgroundThread.IsBackground = true;
_backgroundThread.Start();
}

public long GetCount()
{
lock (_backgroundThread)
{
Program._tickCountUpdateRequest.Set();
Program._tickCountUpdateDone.WaitOne();
return CurrentTickCount;
}
}

private static void _GetCountFunc() {
Random r = new Random();
Program p = new Program();
while (true)
{
// sleep a random amount of time then read
Thread.Sleep(r.Next(20));
lock (System.Console.Out)
{
System.Console.Out.WriteLine("thread " +
Thread.CurrentThread.ManagedThreadId +
": " + p.GetCount().ToString());
}
}
}

static void Main(string[] args)
{
Random r = new Random();
Thread d = new Thread(new ThreadStart(_GetCountFunc));
d.Start();
while (true)
{
Thread a = new Thread(new ThreadStart(_GetCountFunc));
Thread b = new Thread(new ThreadStart(_GetCountFunc));
Thread c = new Thread(new ThreadStart(_GetCountFunc));
a.Start();
b.Start();
c.Start();
Thread.Sleep(r.Next(50));
a.Abort();
Thread.Sleep(r.Next(50));
b.Abort();
c.Abort();
}
}
}
}
 
N

not_a_commie

The conclusion is the same though - you're not setting processor affinity
(which is what you're trying to accomplish), but are rather setting affinity
of the Managed Thread to the O/S thread.

This means your thread can still be scheduled on either processing core,
depending on the circumstances.

I don't really care what processor the background thread runs on. I
just don't want it jumping between two different processors. Will the
OS ever move a thread between processors once it has started running?

Is there a standard way to set processor affinity for threads
in .NET?

My thinking was that an abort would still trigger the "dispose" on the
lock. But I think you're right in saying that it won't. A volatile
flag then seems a better way to do it.
 
C

Chris Mullins [MVP]

not_a_commie said:
I don't really care what processor the background thread runs on. I
just don't want it jumping between two different processors. Will the
OS ever move a thread between processors once it has started running?

From time-slice to time-slice, the O/S can move the thread between
processors. You need to explicitly set processor affinity to prevent that.
Is there a standard way to set processor affinity for threads
in .NET?

Not really. You need to call out to Win32.

The link I sent you, to a Joe Duffy blog entry, shows an example of that
being done.
My thinking was that an abort would still trigger the "dispose" on the
lock. But I think you're right in saying that it won't.

The right answer is to not abort the thread. This will cause you all sorts
of headaches and will never, ever, work perfectly. It's always going to be
prone to bugs. You need a better signaling mechanism.
A volatile flag then seems a better way to do it.

That won't really do it either, and is much more complex than it initially
sounds. Reading and Writing to Volatile variables still needs locks to
insure you don't get read/write tears. There are alot of subtle behaviors
around volatile variables that are best avoided.

If you really need to go down this route, use the various Interlocked
methods, not a volatile variable.
 
W

Willy Denoyette [MVP]

not_a_commie said:
I don't really care what processor the background thread runs on. I
just don't want it jumping between two different processors. Will the
OS ever move a thread between processors once it has started running?


Is there a standard way to set processor affinity for threads
in .NET?

You can specify the processor you want to run your thread on by setting the
ProcessorAffinity property of the System.Diagnostics.ProcessThread class,
but this is soemthing you shouldnt do, really, don't assume you can take
over the role of the scheduler for free, he will bite real hard when he
doesn't like what you are doing. Better is to specify the "prefered"
processor for the thread to run on, by sessting the IdealProcessor property
(of the same class) to the processor number you prefer to have your thread
on. Note however that the latter is something that is allready done by the
OS versions starting with XP and up.


Willy.
 
M

Michael D. Ober

Windows will move a thread between processors if processor affinity is not
set. However, even with processor affinity not set, Windows attempts to
keep a thread on the same processor the entire time it is executable and
still in that processor's L2 cache. If a thread is non-executable for long
enough that it has been flushed from the processor L2 cache, it is eligible
for the first available processor since the cache miss penalty will be
incurred regardless of which processor it is moved to.

Mike Ober.
 
N

not_a_commie

Thanks, everyone, for the fantastic info on this. Supposedly Vista
synchronizes the different motherboard socket tick counts during boot.
Anybody know if this will be back-ported to WinXP? Anybody know if the
current Linux kernels do this?
 

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