【Linux系统编程】:简易线程池

1.利用原生线程库制作线程池

线程池是一种多线程处理形式,它将多个线程预先创建并存储在一个池中,以便需要执行任务时可以直接从池中获取线程,而不是每次都创建新的线程。

1.1 实现原理

  • 线程创建与管理:线程池在初始化时会创建一定数量的线程,并将它们放入线程池中。这些线程在创建后不会立即执行具体的任务,而是处于等待状态,等待有任务分配给它们。
  • 任务队列:当有任务需要执行时,会将任务提交到一个任务队列中。任务队列通常是一个阻塞队列,它可以保证任务的有序性和线程安全。
  • 线程获取任务并执行:线程池中的线程会不断地从任务队列中获取任务,并执行相应的任务逻辑。当一个线程完成一个任务后,它不会被销毁,而是会再次回到任务队列中获取下一个任务,继续执行。

1.2 示例

makefile

threadpool:main.cc
	g++ -o $@ $^ -std=c++11 -lpthread
.PHONY:clean
clean:
	rm -f threadpool

threadpool.hpp

#pragma once
#include <iostream>
#include <pthread.h>
#include <vector>
#include <string>
#include <queue>
#include <unistd.h>
struct ThreadInfo
{
   
    pthread_t tid_;
    std::string name_;
};
static const int defaultnum = 5;
template <typename T>
class ThreadPool
{
   
public:
    void Lock()
    {
   
        pthread_mutex_lock(&mutex_);
    }
    void Unlock()
    {
   
        pthread_mutex_unlock(&mutex_);
    }
    void Wakeup()
    {
   
        pthread_cond_signal(&cond_);
    }
    void ThreadSleep()
    {
   
        pthread_cond_wait(&cond_, &mutex_);
    }
    bool IsQueueEmpty()
    {
   
        bool empty = tasks_.empty();
        return empty;
    }
    std::string GetThreadName(pthread_t tid)
    {
   
        for(ThreadInfo ti : threads_)
        {
   
            if(ti.tid_ == pthread_self())
            {
   
                return ti.name_;
            }
        }
        return "noname";
    }
public:
    ThreadPool(int num = defaultnum) : threads_(num)
    {
   
        pthread_mutex_init(&mutex_, nullptr);
        pthread_cond_init(&cond_, nullptr);
    }
    static void *HandlerTask(void *args)
    {
   
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *> (args);
        std::string name = tp->GetThreadName(pthread_self());
        // 线程该如何执行任务呢?
        while (true)
        {
   
            tp->Lock();//先加锁
            // 1.先检查是否有任务,没有就休眠
            while (tp->IsQueueEmpty()) 
            {
   
                tp->ThreadSleep();
            }
            // 2.有任务,从任务队列中取出
            T task = tp->Pop();
            // 3.释放锁,执行任务
            tp->Unlock();
            task();
            std::cout << name << " is running , result:" <<task.GetResult() << std::endl;
        }
        return nullptr;
    }
    void Start()
    {
   
        // 创建线程
        int num = threads_.size();
        for (int i = 0; i < num; ++i)
        {
   
            threads_[i].name_ = "thread--E" + std::to_string(i + 1);
            pthread_create(&threads_[i].tid_, nullptr, HandlerTask, this);
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值