Is Thread is kernel object ?

2019-02-19 12:50发布

问题:

In this book I read that each instance of the Thread class is actually allocating a kernel object - and this is one of the overheads of using Thread.

As far as I know, the thread is not kernel object (only the process is a kernel object in this case. The thread that the process contains are not kernel objects?)

Can someone explain?

回答1:

Thread is a managed object first, you know the System.Threading.Thread class. It is an internal CLR object next, a C++ class also named Thread. There's rather a massive amount of plumbing involved with it, iceberg style. That plumbing certainly uses kernel objects, five of them. Something you can see in Taskmgr.exe. One of them is the native operating system thread handle, the other four are a bit mysterious but probably are synchronization object handles.

The decoupling of Thread with actual Windows thread objects in .NET 2.0 is pretty infamous. It is only technically possible, nobody well known actually ever implemented a CLR host that made it work. It was an important project for the SQL Server team to implement Thread with fibers and they gave up on it. Couldn't make it reliable enough. Hasn't been tried since that I know of.



回答2:

From MSDN about the instances of Thread:

An operating-system ThreadId has no fixed relationship to a managed thread, because an unmanaged host can control the relationship between managed and unmanaged threads. Specifically, a sophisticated host can use the CLR Hosting API to schedule many managed threads against the same operating system thread, or to move a managed thread between different operating system threads.

There also other kinds of threads or thread-like things in .NET. There are thread from the ThreadPool and there are Tasks. Neither of are AFAIK directly bound to OS threads either.

In summary my understanding of this is that no, .NET threads do not necessarily contain kernel objects.



标签: c# .net clr