c# 线程池实现 只是一个原理性的实现细节内容忽略

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace ThreadPoolImp
{
    public class MyThreadExcutor
    {
        //创建
        private static volatile bool RUNNING = true;

//所有任务都放队列中,让工作线程来消费
        private static ConcurrentQueue<Action> queue = null;

private static HashSet<Worker> workers = new HashSet<Worker>();

private static List<Thread> threadList = new List<Thread>();
        //工作线程数
        int poolSize = 0;
        //核心线程数(创建了多少个工作线程)
        int coreSize = 0;

static bool shutdown = false;
        public MyThreadExcutor(int poolSize)
        {
            this.poolSize = poolSize;
            queue = new ConcurrentQueue<Action>();
        }
        public void Exec(Action action)
        {
            if (action == null) { throw new ArgumentNullException(); }
            if (coreSize < poolSize)
            {
                addThread(action);
            }
            else
            {
                try
                {
                    queue.Enqueue(action);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }

private void addThread(Action action)
        {
            coreSize++;
            Worker worker = new Worker(action);
            workers.Add(worker);
            Thread t = new Thread(worker.Run);
            threadList.Add(t);
            try
            {
                t.Start();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

public void ShutDown()
        {
            RUNNING = false;
            if (workers.Count > 0)
            {
                foreach (Worker item in workers)
                {
                    item.InterruptAll();
                }
            }
            shutdown = true;
            Thread.CurrentThread.Interrupt();
        }
        class Worker
        {
            private readonly static object lockObj = new object();
            public Worker(Action action)
            {
                queue.Enqueue(action);
            }

public void Run()
            {
                while (RUNNING)
                {
                    if (shutdown==true)
                    {
                        Thread.CurrentThread.Interrupt();
                    }
                    Action task = null;
                    try
                    {
                        task = GetTask();
                        if (task != null)
                        {
                            task();
                        }
                        else
                        {
                            Thread.CurrentThread.Interrupt();
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }

public Action GetTask()
            {
                Action result;
                queue.TryDequeue(out result);
                return result;
            }
            public void InterruptAll()
            {
                for (int i = 0; i < threadList.Count; i++)
                {
                    threadList[i].Interrupt();
                }
            }
        }

}
}

原文地址:https://www.cnblogs.com/cppfans140812/p/9638055.html

时间: 2024-08-03 17:06:20

c# 线程池实现 只是一个原理性的实现细节内容忽略的相关文章

JAVA线程池原理源码解析—为什么启动一个线程池,提交一个任务后,Main方法不会退出?

起因 public static void main(String[] args) { ExecutorService service = Executors.newFixedThreadPool(10); service.submit(() -> System.out.println("Hello ")); System.out.println("World"); } 呵呵,执行结果谁都知道,显而易见结论线程池的创建的时候,第一次submit操作会创建Wor

【转】一个故事帮你理解线程和线程池

原文:http://www.code123.cc/2486.html 真的很有意思~~看完理解也可以深一点 我是一个线程, 我一出生就被编了个号: 0x3704,  然后被领到一个昏暗的屋子里,  这里我发现了很多和我一模一样的同伴. 我身边的同伴0x6900 待的时间比较长, 他带着沧桑的口气对我说: 我们线程的宿命就是处理包裹. 把包裹处理完以后还得马上回到这里,否则可能永远回不来了. 我一脸懵懂,包裹,什么包裹? ”不要着急,马上你就会明白了, 我们这里是不养闲人的.“ 果然,没多久,屋子

一个Linux下C线程池的实现

在传统服务器结构中, 常是 有一个总的 监听线程监听有没有新的用户连接服务器, 每当有一个新的 用户进入, 服务器就开启一个新的线程用户处理这 个用户的数据包.这个线程只服务于这个用户 , 当 用户与服务器端关闭连接以后, 服务器端销毁这个线程.然而频繁地开辟与销毁线程极大地占用了系统的资源.而且在大量用户的情况下, 系统为了开辟和销毁线程将浪费大量的时间和资源.线程池提供了一个解决外部大量用户与服务器有限资源的矛盾, 线程池和传统的一个用户对应一个线程的处理方法不同, 它的基本思想就是在程序

理解线程池,自己实现一个线程池

线程池本质是一个生产者-消费者模式,一边维护一些线程执行任务,一边由主线程添加一些任务.现在我们抛弃源码中一些繁杂的状态判断,自己写一个线程池. public class poolT { //可能频繁增删任务,链表队列效率较高 private final BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(); private final HashSet<Work> workers

python创建一个线程和一个线程池

创建一个线程 1.示例代码 import time import threading def task(arg): time.sleep(2) while True: num = input('>>>') t = threading.Thread(target=task.args=(num,)) t.start() 创建一个线程池 1.示例代码 import time from concurrent.futures import ThreadPoolExecutor def task(m

线程基础:线程池(6)——基本使用(中)

(接上文:<线程基础:线程池(5)--基本使用(上)>) 3-4.JAVA主要线程池的继承结构 我们先来总结一下上文中讨论过的内容,首先就是JAVA中ThreadPoolExecutor类的继承结构.如下图所示: ThreadPoolExecutor:这个线程池就是我们这两篇文章中介绍的重点线程池实现.程序员可以通过这个线程池中的submit()方法或者execute()方法,执行所有实现了Runnable接口或者Callable接口的任务:ThreadPoolExecutor对于这些任务的执

12.ThreadPoolExecutor线程池原理及其execute方法

jdk1.7.0_79  对于线程池大部分人可能会用,也知道为什么用.无非就是任务需要异步执行,再者就是线程需要统一管理起来.对于从线程池中获取线程,大部分人可能只知道,我现在需要一个线程来执行一个任务,那我就把任务丢到线程池里,线程池里有空闲的线程就执行,没有空闲的线程就等待.实际上对于线程池的执行原理远远不止这么简单. 在Java并发包中提供了线程池类——ThreadPoolExecutor,实际上更多的我们可能用到的是Executors工厂类为我们提供的线程池:newFixedThread

线程池和异步线程

目录: 1 什么是CLR线程池? 2 简单介绍下线程池各个优点的实现细节 3 线程池ThreadPool的常用方法介绍 4 简单理解下异步线程 5 异步线程的工作过程和几个重要的元素 6 有必要简单介绍下Classic Async Pattern 和Event-based Async Pattern 7 异步线程的发展趋势以及.net4.5异步的简化 8 本章示例 自定义一个简单的线程池 Asp.net异步IHttpAsyncHandler示例 9 本章总结 1 什么是CLR线程池? 在上一章中

.Net多线程编程—Parallel LINQ、线程池

Parallel LINQ 1 System.Linq.ParallelEnumerable 重要方法概览: 1)public static ParallelQuery<TSource> AsParallel<TSource>(this IEnumerable<TSource> source);启用查询的并行化 2)public static ParallelQuery<TSource> AsOrdered<TSource>(this Paral