当前位置: 代码网 > it编程>编程语言>Asp.net > .NET Core 线程池(ThreadPool)底层原理源码解析

.NET Core 线程池(ThreadPool)底层原理源码解析

2025年02月13日 Asp.net 我要评论
简介上文提到,创建线程在操作系统层面有4大无法避免的开销。因此复用线程明显是一个更优的策略,切降低了使用线程的门槛,提高程序员的下限。.net core线程池日新月异,不同版本实现都有差别,在.net

简介

上文提到,创建线程在操作系统层面有4大无法避免的开销。因此复用线程明显是一个更优的策略,切降低了使用线程的门槛,提高程序员的下限。

.net core线程池日新月异,不同版本实现都有差别,在.net 6之前,threadpool底层由c++承载。在之后由c#承载。本文以.net 8.0.8为蓝本,如有出入,请参考源码.

threadpool结构模型图

眼见为实

https://github.com/dotnet/runtime/blob/main/src/libraries/system.private.corelib/src/system/threading/threadpoolworkqueue.cs上源码 and windbg

internal sealed partial class threadpoolworkqueue
{
        internal readonly concurrentqueue<object> workitems = new concurrentqueue<object>();//全局队列
        internal readonly concurrentqueue<object> highpriorityworkitems = new concurrentqueue<object>();//高优先级队列,比如timer产生的定时任务
        internal readonly concurrentqueue<object> lowpriorityworkitems =
            s_prioritizationexperiment ? new concurrentqueue<object>() : null!;//低优先级队列,比如回调
        internal readonly concurrentqueue<object>[] _assignableworkitemqueues =
            new concurrentqueue<object>[s_assignableworkitemqueuecount];//cpu 核心大于32个,全局队列会分裂为好几个,目的是降低cpu核心对全局队列的锁竞争
}

threadpool生产者模型

眼见为实

        public void enqueue(object callback, bool forceglobal)
        {
            debug.assert((callback is ithreadpoolworkitem) ^ (callback is task));
            if (_loggingenabled && frameworkeventsource.log.isenabled())
                frameworkeventsource.log.threadpoolenqueueworkobject(callback);
#if coreclr
            if (s_prioritizationexperiment)//lowpriorityworkitems目前还是实验阶段,clr代码比较偷懒,这一段代码很不优雅,没有连续性。
            {
                enqueueforprioritizationexperiment(callback, forceglobal);
            }
            else
#endif
            {
                threadpoolworkqueuethreadlocals? tl;
                if (!forceglobal && (tl = threadpoolworkqueuethreadlocals.threadlocals) != null)
                {
                    tl.workstealingqueue.localpush(callback);//如果没有特殊情况,默认加入本地队列
                }
                else
                {
                    concurrentqueue<object> queue =
                        s_assignableworkitemqueuecount > 0 && (tl = threadpoolworkqueuethreadlocals.threadlocals) != null
                            ? tl.assignedglobalworkitemqueue//cpu>32 加入分裂的全局队列
                            : workitems;//cpu<=32 加入全局队列
                    queue.enqueue(callback);
                }
            }
            ensurethreadrequested();
        }

细心的朋友,会发现highpriorityworkitems的注入判断哪里去了?目前clr对于高优先级队列只开放给内部,比如timer/task使用

threadpool消费者模型

眼见为实

public object? dequeue(threadpoolworkqueuethreadlocals tl, ref bool missedsteal)
        {
            // check for local work items
            object? workitem = tl.workstealingqueue.localpop();
            if (workitem != null)
            {
                return workitem;
            }
            // check for high-priority work items
            if (tl.isprocessinghighpriorityworkitems)
            {
                if (highpriorityworkitems.trydequeue(out workitem))
                {
                    return workitem;
                }
                tl.isprocessinghighpriorityworkitems = false;
            }
            else if (
                _mayhavehighpriorityworkitems != 0 &&
                interlocked.compareexchange(ref _mayhavehighpriorityworkitems, 0, 1) != 0 &&
                trystartprocessinghighpriorityworkitemsanddequeue(tl, out workitem))
            {
                return workitem;
            }
            // check for work items from the assigned global queue
            if (s_assignableworkitemqueuecount > 0 && tl.assignedglobalworkitemqueue.trydequeue(out workitem))
            {
                return workitem;
            }
            // check for work items from the global queue
            if (workitems.trydequeue(out workitem))
            {
                return workitem;
            }
            // check for work items in other assignable global queues
            uint randomvalue = tl.random.nextuint32();
            if (s_assignableworkitemqueuecount > 0)
            {
                int queueindex = tl.queueindex;
                int c = s_assignableworkitemqueuecount;
                int maxindex = c - 1;
                for (int i = (int)(randomvalue % (uint)c); c > 0; i = i < maxindex ? i + 1 : 0, c--)
                {
                    if (i != queueindex && _assignableworkitemqueues[i].trydequeue(out workitem))
                    {
                        return workitem;
                    }
                }
            }
#if coreclr
            // check for low-priority work items
            if (s_prioritizationexperiment && lowpriorityworkitems.trydequeue(out workitem))
            {
                return workitem;
            }
#endif
            // try to steal from other threads' local work items
            {
                workstealingqueue localwsq = tl.workstealingqueue;
                workstealingqueue[] queues = workstealingqueuelist.queues;
                int c = queues.length;
                debug.assert(c > 0, "there must at least be a queue for this thread.");
                int maxindex = c - 1;
                for (int i = (int)(randomvalue % (uint)c); c > 0; i = i < maxindex ? i + 1 : 0, c--)
                {
                    workstealingqueue otherqueue = queues[i];
                    if (otherqueue != localwsq && otherqueue.cansteal)
                    {
                        workitem = otherqueue.trysteal(ref missedsteal);
                        if (workitem != null)
                        {
                            return workitem;
                        }
                    }
                }
            }
            return null;
        }

什么是线程饥饿?

线程饥饿(thread starvation)是指线程长时间得不到调度(时间片),从而无法完成任务。

  • 线程被无限阻塞
    当某个线程获取锁后长期不释放,其它线程一直在等待
  • 线程优先级降低
    操作系统锁竞争中,高优先级线程,抢占低优先级线程的cpu时间
  • 线程在等待
    比如线程wait/result时,线程池资源不够,导致得不到执行

眼见为实

@一线码农 使用大佬的案例

windbg sos bug依旧存在

大佬的文章中,描述sos存在bug,无法显示线程堆积情况

经实测,在.net 8中依旧存在此bug

99851个积压队列,没有显示出来

threadpool如何改善线程饥饿

clr线程池使用爬山算法来动态调整线程池的大小来来改善线程饥饿的问题。本人水平有限,放出地址,有兴趣的同学可以自行研究https://github.com/dotnet/runtime/blob/main/src/libraries/system.private.corelib/src/system/threading/portablethreadpool.hillclimbing.cs

threadpool如何增加线程

在 portablethreadpool 中有一个子类叫 gatethread,它就是专门用来增减线程的类

其底层使用一个while (true) 每隔500ms来轮询线程数量是否足够,以及一个autoresetevent来接收注入线程event.如果不够就新增

《clr vir c#》 一书中,提过一句 clr线程池每秒最多新增1~2个线程。结论的源头就是在这里注意:是线程池注入线程每秒1~2个,不是每秒只能创建1~2个线程。os创建线程的速度块多了。

眼见为实

https://github.com/dotnet/runtime/blob/main/src/libraries/system.private.corelib/src/system/threading/portablethreadpool.cs

眼见为实

        static void main(string[] args)
        {
            for (int i = 0;i<=100000;i++)
            {
                threadpool.queueuserworkitem((x) =>
                {
                    console.writeline($"当前线程id:{thread.currentthread.managedthreadid}");
                    thread.sleep(int.maxvalue);
                });
            }
            console.readline();
        }

可以观察输出,判断是不是每秒注入1~2个线程

task

不用多说什么了吧?

task的底层调用模型图

task的底层实现主要取决于taskschedule,一般来说,除了ui线程外,默认是调度到线程池

眼见为实

task.run(() => { { console.writeline("test"); } });

其底层会自动调用start(),start()底层调用的taskshedule.queuetask().而作为实现类threadpooltaskscheduler.queuetask底层调用如下。

可以看到,默认情况下(除非你自己实现一个taskshedule抽象类).task的底层使用threadpool来管理。

有意思的是,对于长任务(long task),直接是用一个单独的后台线程来管理,完全不参与调度。

task对线程池的优化

既然task的底层是使用threadpool,而线程池注入速度是比较慢的。task作为线程池的高度封装,有没有优化呢?答案是yes当使用task.result时,底层会调用internalwaitcore(),如果task还未完成,会调用threadpool.notifythreadblocked()来通知threadpool当前线程已经被阻塞,必须马上注入一个新线程来代替被阻塞的线程。相对每500ms来轮询注入线程,该方式采用事件驱动,注入线程池的速度会更快。

眼见为实

  static void main(string[] args)
        {
            var client = new httpclient();
            for(int i = 0; i < 100000; i++)
            {
                threadpool.queueuserworkitem(x =>
                {
                    console.writeline($"{datetime.now.tostring("yyyy-mm-dd hh:mm:ss:fff")} -> {x}: 这是耗时任务");
                    try
                    {
                        var content = client.getstringasync("https://youtube.com").result;
                        console.writeline(content);
                    }
                    catch (exception)
                    {
                        throw;
                    }
                });
            }
            console.readline();
        }

其底层通过autoresetevent来触发注入线程的event消息

结论

多用task,它更完善。对线程池优化更好。没有不使用task的理由

到此这篇关于.net core 线程池(threadpool)底层原理浅谈的文章就介绍到这了,更多相关.net core 线程池threadpool内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com