Code Monkey home page Code Monkey logo

threadpool's Introduction

线程池

基于C++17的线程池

数据结构

工作队列

工作队列是处于运行状态的队列,是运行中的线程。

在线程池启动后,工作队列会一直运行任务队列中的任务,运行完一个后取下一个,如果任务队列没有任务则等待。

这里的任务指用户需要放到线程池里执行的函数

关闭线程池后需要终止工作队列的线程。

任务队列

任务队列是函数的队列,线程池会将传进来的函数“打包”,然后放入任务队列中

这些打包好的函数会被工作队列取出并执行

互斥与条件变量

由于“任务队列”可能会被多个操作同时访问读写,所以需要使用互斥量加锁

同时,工作队列会因为任务队列没有任务进入等待状态,所以需要条件变量在任务队列有任务后通知正在等待的线程

成员函数

启动线程池

根据线程池大小创建工作队列的线程,线程内部是循环,不停的从任务队列取函数运行

添加任务

将传入的函数和其参数“打包”,并放入任务队列中,然后通知正在等待的线程取任务执行

关闭线程池

这部分我将其放在了析构函数里,通过一个“运行标记”记录当前线程池的状态

在析构函数中将其标记为“停止”,这样工作队列的线程检测到标记后,就会退出其所在的线程

threadpool's People

Contributors

zwmain avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.