《ZLToolKit源码学习笔记》(7)线程模块之线程池组件:任务队列与线程组

 系列文章目录

《ZLToolKit源码学习笔记》(1)VS2019源码编译

《ZLToolKit源码学习笔记》(2)工具模块之日志功能分析

《ZLToolKit源码学习笔记》(3)工具模块之终端命令解析

《ZLToolKit源码学习笔记》(4)工具模块之消息广播器

《ZLToolKit源码学习笔记》(5)工具模块之资源池

《ZLToolKit源码学习笔记》(6)线程模块之整体框架概述

《ZLToolKit源码学习笔记》(7)线程模块之线程池组件:任务队列与线程组(本文)

《ZLToolKit源码学习笔记》(8)线程模块之线程负载计算器

《ZLToolKit源码学习笔记》(9)线程模块之任务执行器

《ZLToolKit源码学习笔记》(10)线程模块之线程池

《ZLToolKit源码学习笔记》(11)线程模块之工作线程池WorkThreadPool

《ZLToolKit源码学习笔记》(12)事件轮询模块之整体框架概述

《ZLToolKit源码学习笔记》(13)事件轮询模块之管道的简单封装

《ZLToolKit源码学习笔记》(14)事件轮询模块之定时器

《ZLToolKit源码学习笔记》(15)事件轮询模块之事件轮询器EventPoller

《ZLToolKit源码学习笔记》(16)网络模块之整体框架概述

《ZLToolKit源码学习笔记》(17)网络模块之基础接口封装类SockUtil

《ZLToolKit源码学习笔记》(18)网络模块之Buffer缓存

《ZLToolKit源码学习笔记》(19)网络模块之套接字封装

《ZLToolKit源码学习笔记》(20)网络模块之TcpServer

《ZLToolKit源码学习笔记》(21)网络模块之TcpClient与Session

《ZLToolKit源码学习笔记》(22)网络模块之UdpServer


前言

在学习线程池之前,先看下线程池的两个基本组件:任务队列与线程组。


目录

 系列文章目录

前言

一、任务队列TaskQueue

1.1、semaphore

1.2、TaskQueue接口分析

1.2.1、添加任务至队列

1.2.2、从队列中获取一个任务

1.2.3、清空任务列队(让get_task接口返回false)

 二、线程组thread_group

2.1、判断当前线程是否在线程组中

2.2、判断指定的线程是否在线程组中

2.3、添加线程

2.4、删除线程

2.5、等待线程组中所有线程退出


一、任务队列TaskQueue

封装TaskQueue类,提供了添加任务、获取任务、清空任务队列接口,通过semaphore控制添加与获取之间的同步。

template<typename T>
class TaskQueue {
public:
    //添加任务
    template<typename C>
    void push_task(C &&task_func);
    template<typename C>
    void push_task_first(C &&task_func);
    //清空任务列队
    void push_exit(size_t n);
    //获取任务
 bool get_task(T &tsk);
    size_t size();
private:
    List<T> _queue;
    mutable mutex _mutex;
    semaphore _sem;
};

1.1、semaphore

封装条件变量condition_variable_any的使用,提供了post和wait接口。

void post(size_t n = 1) {
    unique_lock<mutex> lock(_mutex);
    _count += n;
    if(n == 1){
        _condition.notify_one();
    }else{
        _condition.notify_all();
    }
}

void wait() {
    unique_lock<mutex> lock(_mutex);
    while (_count == 0) {
        _condition.wait(lock);
    }
    --_count;
}

 _count成员记录希望wait接口返回的次数。默认情况下,每调用一次post,_count加1,通过notify_one,所有等待在_condition.wait上的线程其中一个被唤醒。如果n大于1,将通过notify_all唤醒所有等待在_condition.wait上的线程。

对于生产者消费者模型,count记录产品数量,post每次生产一个或者多个产品,wait每次消费一个产品,wait被唤醒后,会一直执行,直到产品都被消耗完。

在线程池的实现中,作者通过在没有添加任务的情况下,调用post(n>1)来控制线程的退出。

1.2、TaskQueue接口分析

1.2.1、添加任务至队列

template<typename C>
void push_task(C &&task_func) {
    {
        lock_guard<decltype(_mutex)> lock(_mutex);
        _queue.emplace_back(std::forward<C>(task_func));
    }
    _sem.post();
}

template<typename C>
void push_task_first(C &&task_func) {
    {
        lock_guard<decltype(_mutex)> lock(_mutex);
        _queue.emplace_front(std::forward<C>(task_func));
    }
    _sem.post();
}

push_task在队列的尾部添加任务,push_task_first在队列的头部添加任务。

为什么不直接使用void push_task(T &&task_func)而要用模板呢?

template<typename C> void push_task(C &&task_func);
void push_task(T &&task_func);
void push_task(T &task_func);
void push_task(const T &task_func);

 push_task(T &&task_func)只能接受右值引用,push_task(T &task_func)不能接受右值引用,push_task(const T &task_func)接受右值时会产生临时变量。模板因为引用折叠,既能接受左值,也能接受右值。

1.2.2、从队列中获取一个任务

bool get_task(T &tsk) {
    _sem.wait();
    lock_guard<decltype(_mutex)> lock(_mutex);
    if (_queue.size() == 0) {
        return false;
    }
    //改成右值引用后性能提升了1倍多!
    tsk = std::move(_queue.front());
    _queue.pop_front();
    return true;
}

 阻塞在条件变量上,等待队列中添加任务或者通过push_exit主动退出。

1.2.3、清空任务列队(让get_task接口返回false)

void push_exit(size_t n) {
    _sem.post(n);
}

任务的数量由semaphore类中的_count成员控制,正常情况下,每给队列添加一个任务,触发一次_sem.post(1),任务数量加1,每次wait返回时,队列中都是有任务的,get_task总能获取到一个任务,返回true。此处,在实际没有给队列中添加任务的情况下,让wait多返回了n次,这n次get_task肯定是获取不到任务的,会返回false。线程池中利用get_task返回false来达到退出线程的目的。如启动了4个工作线程来获取任务,每个线程都等待在get_task上,主线程中调用push_exit(4),get_task就会有四次返回false,以此让工作线程退出。


 二、线程组thread_group

管理一组线程,接口:添加线程、删除线程、等待线程组中所有线程退出、判断指定的线程是否在线程组中、判断当前线程是否在线程组中。

2.1、判断当前线程是否在线程组中

bool is_this_thread_in() {
    auto thread_id = this_thread::get_id();
    if(_thread_id == thread_id){//意义是?比unordered_map遍历快?为了提高运行效率?
        return true;
    }
    return _threads.find(thread_id) != _threads.end();
}

2.2、判断指定的线程是否在线程组中

bool is_thread_in(thread* thrd) {
    if (!thrd) {
        return false;
    }
    auto it = _threads.find(thrd->get_id());
    return it != _threads.end();
}

2.3、添加线程

template<typename F>
thread* create_thread(F &&threadfunc) {
    auto thread_new = std::make_shared<thread>(threadfunc);
    _thread_id = thread_new->get_id();
    _threads[_thread_id] = thread_new;
    return thread_new.get();
}

2.4、删除线程

void remove_thread(thread* thrd) {
    auto it = _threads.find(thrd->get_id());
    if (it != _threads.end()) {
        _threads.erase(it);
    }
}

2.5、等待线程组中所有线程退出

void join_all() {
    if (is_this_thread_in()) {
        throw runtime_error("thread_group: trying joining itself");
    }
    for (auto &it : _threads) {
        if (it.second->joinable()) {
            it.second->join(); //等待线程主动退出
        }
    }
    _threads.clear();
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
好的,下面是Java多线程编程学习笔记之十二:生产者—消费者模型的相关内容和代码。 ## 生产者—消费者模型简介 生产者—消费者模型是一种常见的多线程并发模型,它涉及到两个角色:生产者和消费者。生产者负责生产数据,消费者负责消费数据。生产者和消费者通过一个共享的缓冲区进行通信,生产者将数据放入缓冲区,消费者从缓冲区获取数据。 在多线程编程中,生产者—消费者模型的实现有多种方式,本文将介绍一种基于Java的实现方式。 ## 生产者—消费者模型的实现 ### 1. 定义共享缓冲区 共享缓冲区是生产者和消费者进行通信的桥梁,它需要实现以下功能: - 提供一个put方法,允许生产者将数据放入缓冲区; - 提供一个take方法,允许消费者从缓冲区获取数据; - 当缓冲区已满时,put方法应该等待; - 当缓冲区为空时,take方法应该等待。 以下是一个简单的共享缓冲区的实现: ```java public class Buffer { private int[] data; private int size; private int count; private int putIndex; private int takeIndex; public Buffer(int size) { this.data = new int[size]; this.size = size; this.count = 0; this.putIndex = 0; this.takeIndex = 0; } public synchronized void put(int value) throws InterruptedException { while (count == size) { wait(); } data[putIndex] = value; putIndex = (putIndex + 1) % size; count++; notifyAll(); } public synchronized int take() throws InterruptedException { while (count == 0) { wait(); } int value = data[takeIndex]; takeIndex = (takeIndex + 1) % size; count--; notifyAll(); return value; } } ``` 上面的Buffer类使用一个数来表示缓冲区,size表示缓冲区的大小,count表示当前缓冲区中的元素数量,putIndex和takeIndex分别表示下一个可写和可读的位置。put和take方法都是同步方法,使用wait和notifyAll来进行线程间的等待和通知。 ### 2. 定义生产者和消费者 生产者和消费者都需要访问共享缓冲区,因此它们都需要接收一个Buffer对象作为参数。以下是生产者和消费者的简单实现: ```java public class Producer implements Runnable { private Buffer buffer; public Producer(Buffer buffer) { this.buffer = buffer; } public void run() { try { for (int i = 0; i < 10; i++) { buffer.put(i); System.out.println("Produced: " + i); Thread.sleep((int)(Math.random() * 1000)); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class Consumer implements Runnable { private Buffer buffer; public Consumer(Buffer buffer) { this.buffer = buffer; } public void run() { try { for (int i = 0; i < 10; i++) { int value = buffer.take(); System.out.println("Consumed: " + value); Thread.sleep((int)(Math.random() * 1000)); } } catch (InterruptedException e) { e.printStackTrace(); } } } ``` 生产者在一个循环中不断地向缓冲区中放入数据,消费者也在一个循环中不断地从缓冲区中获取数据。注意,当缓冲区已满时,生产者会进入等待状态;当缓冲区为空时,消费者会进入等待状态。 ### 3. 测试 最后,我们可以使用下面的代码来进行测试: ```java public class Main { public static void main(String[] args) { Buffer buffer = new Buffer(5); Producer producer = new Producer(buffer); Consumer consumer = new Consumer(buffer); Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); } } ``` 在上面的代码中,我们创建了一个缓冲区对象和一个生产者对象和一个消费者对象,然后将它们分别传递给两个线程,并启动这两个线程。 运行上面的代码,我们可以看到生产者和消费者交替地进行操作,生产者不断地向缓冲区中放入数据,消费者不断地从缓冲区中获取数据。如果缓冲区已满或者为空,生产者和消费者会进入等待状态,直到缓冲区中有足够的空间或者有新的数据可用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秦时小

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值