栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++线程池实现

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++线程池实现

1.写出一个单例

class Threadpool
{
private:
    Threadpool(){}
    static Threadpool threadpool;

public:
    static Threadpool* getInstance(){ return &threadpool; } 

};
Threadpool Threadpool::threadpool;

其中最容易忽视的一句是:Threadpool Threadpool::threadpool;

2.设计函数

public:
void start()

void addTask(task task_)

private:
void Runtask()
//用于给start绑定

3.设计一个线程池,一个任务队列

vector threadList;//线程池

//任务队列
using task = function;
queue tasks;

4.使用Linux信号量

sem_t taskSem;

sem_init(&taskSem, 0, 0);

sem_post(&taskSem);

sem_wait(&taskSem);

5.任务存放到任务队列中并使用 sem_post( ) 通知 sem_wait( ) ;

tasks.push(task_);

sem_post(&taskSem);
//信号量+1

6.收到通知,从任务队列中取出任务并执行

sem_wait(&taskSem);
//收到通知开始执行

task task__;
task__ = tasks.front();
//拿到第一个任务

tasks.pop();
//丢弃第一个任务

task__();
//执行第一个任务

7.开启线程池,往线程池里添加N个线程

for(int i = 0; i < 15; i++)
   {
        threadList.push_back(thread(&Threadpoll::Runtask, this));
   }

8.附源码

#include 
#include 
#include 
#include 
#include 
#include 
#include 


using namespace std;

sem_t taskSem;
int poolSize = 10;

class Threadpool
{
private:
    using task = function;

    Threadpool()
    {
        sem_init(&taskSem, 0, 0);
    }
    static Threadpool threadpool;

private:
    vector threadList;
    queue tasks;

public:
    static Threadpool* getInstance(){ return &threadpool; } 

    void addTask(task task_)
    {
        tasks.push(task_);

        sem_post(&taskSem);
    }

    void Runtask()
    {
        sem_wait(&taskSem);
        
        task task__;
        task__ = tasks.front();

        tasks.pop();

        task__();
    }

    void start()
    {
        for(int i = 0; i < 15; i++)
        {
            threadList.push_back(thread(&Threadpool::Runtask, this));
        }
    }

};
Threadpool Threadpool::threadpool;
//这句话很重要

9.测试

void func1()
{
    cout<<"hello world"<start();
    
    while(1)
    {
        sleep(2);
        instance->addTask(func1);
    }


    return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1029604.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号