8
votes

I was reading about the System.Threading.DispatcherObject type at this link http://msdn.microsoft.com/en-us/library/ms750441.aspx

The article mentions about one to one relationship between logical and physical thread. Here is the snippet from the article:

During the design phase of WPF, the goal was to move to a single thread of execution, but a non-thread "affinitized" model. Thread affinity happens when a component uses the identity of the executing thread to store some type of state. The most common form of this is to use the thread local store (TLS) to store state. Thread affinity requires that each logical thread of execution be owned by only one physical thread in the operating system, which can become memory intensive

Can someone pls. explain what is the difference between logical vs physical thread ?

2
The next sentence is the one that really matters. They just did the way any GUI class library on Windows works. Brevity was never a WPF architect's asset.Hans Passant

2 Answers

6
votes

A local thread is a thread within the runtime. This thread is more lightweight than a full fledged physical thread and are good for lighter weight processes. A physical thread is a thread that a processor context switches to and processes. It has more meta data associated with it as the operating system keeps track of it. There is a lot more detail involved, but that's a quick overview.

The physical thread in that case would contain these logical "virtual threads" internally.

1
votes

The CLR of .NET 2.0 did plan to have fiber support as .NET Thread for SQL CLR. It did never make it into the product but it could be that in a distant future the CLR will support it. Hence this big red thread affinity warning.

The OS does support fibers natively but they are quite hard to use correctly since you are switching in and out your stack in user mode to let other code run on the same physical thread. This does eliminate costly context switches which can make sense in some high performance scenarios. To use fibers as abstractions is hardly a good idea since you cannot call any third party library since you do not know if the api does assume thread affinity or not.

The cost of context switches in todays multi core machines is much less than it was several Windows versions and processor generations earlier. I doubt that you will gain much with fibers in a real world application. Besides this the chip makers are working hard to make the cost of context switches even less. There are designs discussed to make it as cheap as one CPU cycle.

To make a long story short:

It could happen that the CLR Thread object is not a physical OS thread if you host the CLR by yourself and use a not (yet) existing feature of the CLR hosting APIs.

As far as I do know the Window message pump system will stay there even in Windows 8 where each window has thread affinity to the creating thread which must also pump the window messages.