为了好玩,我编写了这段代码来模拟死锁.然后,我坐着看着它耐心地运行,直到线程池已经降到零的可用工作线程的总数.我很想知道会发生什么.会抛出异常吗?
using System;
using System.Diagnostics;
using System.Threading;
namespace Deadlock
{
class Program
{
private static readonly object lockA = new object();
private static readonly object lockB = new object();
static void Main(string[] args)
{
int worker, io;
ThreadPool.GetAvailableThreads(out worker, out io);
Console.WriteLine($"Total number of thread pool threads: {worker}, {io}");
Console.WriteLine($"Total threads in my process: {Process.GetCurrentProcess().Threads.Count}");
Console.ReadKey();
try
{
for (int i = 0; i < 1000000; i++)
{
AutoResetEvent auto1 = new AutoResetEvent(false);
AutoResetEvent auto2 = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(ThreadProc1, auto1); …Run Code Online (Sandbox Code Playgroud) 最近我正在研究操作系统,并遇到了这个问题.
线程是在C#用户级别还是内核级别创建的,如:
Thread mythread=new Thread(ThreadStart(something));
Run Code Online (Sandbox Code Playgroud)
据我所知,内核级别的cpu密集型线程的运行速度可能比用户级别的运行速度快. 因为现代操作系统这本书说"用户级线程的时间表不会陷入内核,这就是为什么它们与kernl级线程相比更轻量级".
所以我认为用户级线程无法在不同的cpu上运行,这需要陷入内核.
在linux中,创建的线程pthread_create是内核级别.所以我对.Net C#的功能感到好奇.