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.Collecti ons.Generic;
using System.Text;
using System.Threadin g;
namespace TestThreading
{
public sealed class Program
{
static private Thread _backgroundThre ad = null;
static private EventWaitHandle _tickCountUpdat eRequest = new
EventWaitHandle (false, EventResetMode. AutoReset);
static private EventWaitHandle _tickCountUpdat eDone = new
EventWaitHandle (false, EventResetMode. AutoReset);
static public long CurrentTickCoun t = 0;
private static void _BackgroundThre adFunc()
{
Thread.BeginThr eadAffinity(); // always read the tick count from
the same CPU -- not necessary in Vista
while (true)
{
_tickCountUpdat eRequest.WaitOn e();
CurrentTickCoun t = System.Diagnost ics.Stopwatch.G etTimestamp();
_tickCountUpdat eDone.Set();
}
Thread.EndThrea dAffinity(); // never called; but here for symmetry
}
static Program() {
_backgroundThre ad = new Thread(new
ThreadStart(_Ba ckgroundThreadF unc));
_backgroundThre ad.IsBackground = true;
_backgroundThre ad.Start();
}
public long GetCount()
{
lock (_backgroundThr ead)
{
Program._tickCo untUpdateReques t.Set();
Program._tickCo untUpdateDone.W aitOne();
return CurrentTickCoun t;
}
}
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.CurrentT hread.ManagedTh readId +
": " + p.GetCount().To String());
}
}
}
static void Main(string[] args)
{
Random r = new Random();
Thread d = new Thread(new ThreadStart(_Ge tCountFunc));
d.Start();
while (true)
{
Thread a = new Thread(new ThreadStart(_Ge tCountFunc));
Thread b = new Thread(new ThreadStart(_Ge tCountFunc));
Thread c = new Thread(new ThreadStart(_Ge tCountFunc));
a.Start();
b.Start();
c.Start();
Thread.Sleep(r. Next(50));
a.Abort();
Thread.Sleep(r. Next(50));
b.Abort();
c.Abort();
}
}
}
} 7 1793
I have to confess, I'm completly missing what you're trying to accomplish
here.
Why are you trying to accomplish with Begin/EndThreadAffini ty? 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...9a3980e6d.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_comm ie" <no********@gma il.comwrote in message
news:11******** *************@o 5g2000hsb.googl egroups.com...
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.Collecti ons.Generic;
using System.Text;
using System.Threadin g;
namespace TestThreading
{
public sealed class Program
{
static private Thread _backgroundThre ad = null;
static private EventWaitHandle _tickCountUpdat eRequest = new
EventWaitHandle (false, EventResetMode. AutoReset);
static private EventWaitHandle _tickCountUpdat eDone = new
EventWaitHandle (false, EventResetMode. AutoReset);
static public long CurrentTickCoun t = 0;
private static void _BackgroundThre adFunc()
{
Thread.BeginThr eadAffinity(); // always read the tick count from
the same CPU -- not necessary in Vista
while (true)
{
_tickCountUpdat eRequest.WaitOn e();
CurrentTickCoun t = System.Diagnost ics.Stopwatch.G etTimestamp();
_tickCountUpdat eDone.Set();
}
Thread.EndThrea dAffinity(); // never called; but here for symmetry
}
static Program() {
_backgroundThre ad = new Thread(new
ThreadStart(_Ba ckgroundThreadF unc));
_backgroundThre ad.IsBackground = true;
_backgroundThre ad.Start();
}
public long GetCount()
{
lock (_backgroundThr ead)
{
Program._tickCo untUpdateReques t.Set();
Program._tickCo untUpdateDone.W aitOne();
return CurrentTickCoun t;
}
}
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.CurrentT hread.ManagedTh readId +
": " + p.GetCount().To String());
}
}
}
static void Main(string[] args)
{
Random r = new Random();
Thread d = new Thread(new ThreadStart(_Ge tCountFunc));
d.Start();
while (true)
{
Thread a = new Thread(new ThreadStart(_Ge tCountFunc));
Thread b = new Thread(new ThreadStart(_Ge tCountFunc));
Thread c = new Thread(new ThreadStart(_Ge tCountFunc));
a.Start();
b.Start();
c.Start();
Thread.Sleep(r. Next(50));
a.Abort();
Thread.Sleep(r. Next(50));
b.Abort();
c.Abort();
}
}
}
}
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 [MVP]" <cm******@yahoo .comwrote in message
news:%2******** ********@TK2MSF TNGP05.phx.gbl. ..
>I have to confess, I'm completly missing what you're trying to accomplish here.
Why are you trying to accomplish with Begin/EndThreadAffini ty? 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...9a3980e6d.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_comm ie" <no********@gma il.comwrote in message
news:11******** *************@o 5g2000hsb.googl egroups.com...
>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.Collecti ons.Generic; using System.Text; using System.Threadin g;
namespace TestThreading { public sealed class Program { static private Thread _backgroundThre ad = null; static private EventWaitHandle _tickCountUpdat eRequest = new EventWaitHandl e(false, EventResetMode. AutoReset); static private EventWaitHandle _tickCountUpdat eDone = new EventWaitHandl e(false, EventResetMode. AutoReset); static public long CurrentTickCoun t = 0; private static void _BackgroundThre adFunc() { Thread.BeginTh readAffinity(); // always read the tick count from the same CPU -- not necessary in Vista while (true) { _tickCountUpda teRequest.WaitO ne(); CurrentTickCou nt = System.Diagnost ics.Stopwatch.G etTimestamp(); _tickCountUpda teDone.Set(); } Thread.EndThre adAffinity(); // never called; but here for symmetry }
static Program() { _backgroundThr ead = new Thread(new ThreadStart(_B ackgroundThread Func)); _backgroundThr ead.IsBackgroun d = true; _backgroundThr ead.Start(); }
public long GetCount() { lock (_backgroundThr ead) { Program._tickC ountUpdateReque st.Set(); Program._tickC ountUpdateDone. WaitOne(); return CurrentTickCoun t; } }
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.Current Thread.ManagedT hreadId + ": " + p.GetCount().To String()); } } }
static void Main(string[] args) { Random r = new Random(); Thread d = new Thread(new ThreadStart(_Ge tCountFunc)); d.Start(); while (true) { Thread a = new Thread(new ThreadStart(_Ge tCountFunc)); Thread b = new Thread(new ThreadStart(_Ge tCountFunc)); Thread c = new Thread(new ThreadStart(_Ge tCountFunc)); a.Start(); b.Start(); c.Start(); Thread.Sleep(r .Next(50)); a.Abort(); Thread.Sleep(r .Next(50)); b.Abort(); c.Abort(); } } } }
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.
"not_a_comm ie" <no********@gma il.comwrote
>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?
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.
--
Chris Mullins, MCSD.NET, MCPD:Enterprise , Microsoft C# MVP http://www.coversant.com/blogs/cmullins
"not_a_comm ie" <no********@gma il.comwrote in message
news:11******** *************@n 35g2000prd.goog legroups.com...
>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?
You can specify the processor you want to run your thread on by setting the
ProcessorAffini ty property of the System.Diagnost ics.ProcessThre ad 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.
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.
"not_a_comm ie" <no********@gma il.comwrote in message
news:11******** *************@n 35g2000prd.goog legroups.com...
>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.
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? This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Anthony_Barker |
last post by:
I have been reading a book about the evolution of the Basic
programming language. The author states that Basic - particularly
Microsoft's version is full of compromises which crept in along the
language's 30+ year evolution.
What to you think python largest compromises are?
The three that come to my mind are significant whitespace, dynamic
typing, and that it is interpreted - not compiled. These three put
python under fire and cause...
|
by: Jon Skeet [C# MVP] |
last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the
article on all the groups this is posted to.
I've finally managed to finish my article on multi-threading - at least
for the moment. I'd be *very* grateful if people with any interest in
multi-threading would read it (even just bits of it - it's somewhat
long to go through the whole thing!) to check for accuracy,
effectiveness of examples, etc.
Feel free to mail...
|
by: Z D |
last post by:
Hello,
I'm having a strange problem that is probably due to my lack of
understanding of how threading & COM Interop works in a WinForms.NET
application.
Here's the situation:
I have a 3rd party COM component that takes about 5 seconds to run one of
its functions (Network IO bound call). Since I dont want my GUI to freeze
|
by: [Yosi] |
last post by:
I create new thread as following:
Thread mThread = new Thread(new ThreadStart(m_ClassThread.Go));
In my system I have 2 Process devices ,(CPU0 and CPU1) , I want to create 3
Threads, 2 of those thread to run in CPU0 and the last one in CPU1 , I get
some advice to use the ProcessThread.ProcessorAffinity which seems OK to me .
The problem is how and where to use it ?
Should I change the :
Thread mThread = new Thread(new...
|
by: MuZZy |
last post by:
Hi,
I'm currently rewriting some functionality which was using
multithredaing for retrieving datasets from database and updating a grid
control. I found that the grids (Infragistics UltraGrid, though it
doesn't matter) were updated (i.e. grid.DataSource = dsDataSet;) and
used for different purposes in the worker thread, so now i'm wrapping
all those calls to grid's methods thru invoking which is a pain in the
a$$ considering number of...
| |
by: Frankie |
last post by:
Just getting my feet wet with threading...
Is it the case that... once a method starts executing in a given thread,
that method will finish executing on that same thread? Or is it
possible for a given method to begin executing on a thread, and then finish
executing on another thread. I would think the former is true and the latter
false. Correct?
Thanks!
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |