C++ 线程池 + 消息队列 代码实现

122 篇文章 1 订阅
120 篇文章 1 订阅

1. 消息队列- ConcurrentQueue

在这里插入图片描述
在这里插入图片描述

消息队列用一个类:ConcurrentQueue进行封装,拥有成员**_queue**,来存放元素;内部实现pushpop函数,来对队列进行入队和出队操作。

message_queue.h

#ifndef NET_FRAME_CONCURRENT_QUEUE_H
#define NET_FRAME_CONCURRENT_QUEUE_H
 
#include <queue>
#include <mutex>
#include <condition_variable>

template<class Type>
/*消息队列实现*/
class ConcurrentQueue {
    ConcurrentQueue& operator=(const ConcurrentQueue&) = delete;

    ConcurrentQueue(const ConcurrentQueue& other) = delete;

public:
    ConcurrentQueue() : _queue(), _mutex(), _condition() { }

    virtual ~ConcurrentQueue() { }

    void Push(Type record) {
        std::lock_guard <std::mutex> lock(_mutex);
        _queue.push(record);
        //每增加一个元素,用条件变量进行通知。
        _condition.notify_one();
    }

    bool Pop(Type& record, bool isBlocked = true) {
        if (isBlocked) {
            std::unique_lock <std::mutex> lock(_mutex);
            //当队列为空就进行wait阻塞等待。
            while (_queue.empty()) {
                _condition.wait(lock);
            }
        }
        else // If user wants to retrieve data in non-blocking mode
        {
            std::lock_guard <std::mutex> lock(_mutex);
            if (_queue.empty()) {
                return false;
            }
        }

        record = std::move(_queue.front());
        _queue.pop();
        return true;
    }

    int32_t Size() {
        std::lock_guard <std::mutex> lock(_mutex);
        return _queue.size();
    }

    bool Empty() {
        std::lock_guard <std::mutex> lock(_mutex);
        return _queue.empty();
    }

private:
    std::queue <Type> _queue;
    mutable std::mutex _mutex;
    std::condition_variable _condition;
};
 
 
#endif //NET_FRAME_CONCURRENT_QUEUE_H

2. 线程池-ThreadPool

封装了ThreadPool类,该类需要指定线程的数量_threads,包含用来存放线程的_workers容器。
在创建线程的时候,需要指定线程的处理函数lambda表达式以及元素的处理函数_handler:将消息队列的元素取出,然后作为_handler函数的形参进行处理。

在这里插入图片描述

Submit方法用于往消息队列里增加元素。

在这里插入图片描述
thread_pool.h

#ifndef NET_FRAME_THREAD_POOL_H
#define NET_FRAME_THREAD_POOL_H
 
#include "message_queue.h"
 
#include <vector>
#include <queue>
#include <memory>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <functional>
#include <stdexcept>
 
#define MIN_THREADS 10
 
 
template<class Type>
class ThreadPool {
    ThreadPool& operator=(const ThreadPool&) = delete;

    ThreadPool(const ThreadPool& other) = delete;

public:
    ThreadPool(int32_t threads, std::function<void(Type& record)> handler);

    virtual ~ThreadPool();

    void Submit(Type record);

private:

private:
    bool _shutdown;
    int32_t _threads;
    std::function<void(Type& record)> _handler;
    std::vector <std::thread> _workers;
    ConcurrentQueue <Type> _tasks;
};

template<class Type>
ThreadPool<Type>::ThreadPool(int32_t threads, std::function<void(Type &record)> handler)
        : _shutdown(false),
            _threads(threads),
            _handler(handler),
            _workers(),
            _tasks() {
    if (_threads < MIN_THREADS)
        _threads = MIN_THREADS;


    for (int32_t i = 0; i < _threads; ++i)
        _workers.emplace_back(
                [this] {
                    while (!_shutdown) {
                        Type record;
                        this->_tasks.Pop(record, true);
                        this->_handler(record);
                    }
                }
        );
}


template<class Type>
ThreadPool<Type>::~ThreadPool() {
    for (std::thread &worker: _workers)
        worker.join();
}


template<class Type>
void ThreadPool<Type>::Submit(Type record) {
    _tasks.Push(record);
}
 
 
 
 
#endif //NET_FRAME_THREAD_POOL_H

3. 测试代码

#include"message_queue.h"
#include"thread_pool.h"
#include<iostream>

std::mutex mutex_;

void threadProcess(int value){
    std::unique_lock<std::mutex> lock_(mutex_);
    std::cout<<"current threadId:"<<std::this_thread::get_id()<<" value:"<<value<<std::endl;
}
int main(){
    std::cout<<"main threadId:"<<std::this_thread::get_id()<<std::endl;
    ThreadPool<int> threadPool(15,threadProcess);
    for(int i=0;i<100000;++i){
        threadPool.Submit(i);
    }
    return 0;
}

4.运行截图

在这里插入图片描述

ps-ef |grep main
在这里插入图片描述
top -H -p 23796
可以看出有16个进程正在运行。

在这里插入图片描述

  • 4
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: C语言的线程池代码实现可以在GitHub上找到很多开源项目,以下是其中一个例子: https://github.com/rxi/dyad 这是一个简单的C语言线程池实现,主要使用了POSIX线程库,代码非常简洁和易于理解。它包含一个pool结构体,用于管理线程池的状态和任务队列等信息。主要函数包括pool_init用于初始化线程池,pool_submit用于提交任务,pool_wait用于等待线程池执行完所有任务,pool_destroy用于销毁线程池。 使用这个线程池框架,只需要简单地定义一个任务函数,并通过pool_submit提交任务,即可由线程池中的线程来执行任务。线程池内部会自动调度任务,并根据设置的线程池大小控制并发执行的线程数。 这个线程池实现还提供了一些额外的功能,例如支持任务超时设置,可以在任务执行的一定时间内获取任务的返回结果,也可以设置任务的最大重试次数。 通过在GitHub上搜索"C thread pool"关键词,还可以找到其他很多C语言线程池实现,这些开源项目提供了完整的代码实现和详细的文档说明,可以根据个人需求选择使用。 ### 回答2: 线程池是一种用于管理和复用线程的技术,通过预先创建一组线程并将其放入池中,以便在需要的时候可以重复使用。这样可以避免频繁创建和销毁线程的开销,提高系统的性能和效率。 在GitHub上有很多关于线程池实现代码库,我以下将以Java语言为例来介绍一个常见的线程池实现。 Java的线程池是通过`ThreadPoolExecutor`类来实现的。我们可以在GitHub上搜索"ThreadPoolExecutor"关键字,就会找到很多相关的代码库。 比如,一个名为"java线程池的简单实现"的代码库,这个库提供了一个简单的线程池实现,包括线程池类`MyThreadPoolExecutor`和任务类`MyTask`。通过查看代码,可以了解到该线程池实现了以下几个功能: 1. 创建线程池:通过`MyThreadPoolExecutor`类的构造函数可以指定线程池的大小和其他相关的参数。 2. 提交任务:通过调用`MyThreadPoolExecutor`类的`submit()`方法将任务提交到线程池中。 3. 执行任务:线程池会自动管理和调度线程,并调用任务的`run()`方法来执行任务。 4. 监控线程池:可以通过`MyThreadPoolExecutor`类提供的方法获取线程池的状态,比如当前活动的线程数、完成的任务数等。 5. 终止线程池:通过调用`MyThreadPoolExecutor`类的`shutdown()`方法可以优雅地关闭线程池,等待当前正在执行的任务完成后再关闭线程池。 这只是一个简单的线程池实现,如果对线程池实现原理和更高级的应用有兴趣,可以进一步了解和探索更多的线程池实现代码库。 ### 回答3: C语言中的线程池可以通过使用Pthreads库来实现。以下是一个简单的C语言线程池代码实现,你可以在GitHub上找到完整的代码。 #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define MAX_THREADS 10 #define MAX_QUEUE 1000 typedef struct { void (*function)(void *); // 线程执行的函数指针 void *argument; // 函数参数 } task_t; task_t task_queue[MAX_QUEUE]; int queue_size = 0; int head = 0; int tail = 0; pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t queue_cond = PTHREAD_COND_INITIALIZER; pthread_t worker_threads[MAX_THREADS]; int pool_shutdown = 0; // 添加任务到线程池 void pool_add_task(void (*function)(void *), void *argument) { pthread_mutex_lock(&queue_mutex); if (queue_size >= MAX_QUEUE) { fprintf(stderr, "Warning: task queue is full, the task is dropped.\n"); pthread_mutex_unlock(&queue_mutex); return; } task_queue[tail].function = function; task_queue[tail].argument = argument; tail = (tail + 1) % MAX_QUEUE; queue_size++; pthread_cond_signal(&queue_cond); pthread_mutex_unlock(&queue_mutex); } // 线程池的工作线程函数 void *worker(void *arg) { while (1) { pthread_mutex_lock(&queue_mutex); while (queue_size == 0 && !pool_shutdown) { pthread_cond_wait(&queue_cond, &queue_mutex); } if (pool_shutdown) { pthread_mutex_unlock(&queue_mutex); pthread_exit(NULL); } void (*function)(void *) = task_queue[head].function; void *argument = task_queue[head].argument; head = (head + 1) % MAX_QUEUE; queue_size--; pthread_mutex_unlock(&queue_mutex); function(argument); } } // 初始化线程池 void pool_init() { int i; for (i = 0; i < MAX_THREADS; i++) { pthread_create(&worker_threads[i], NULL, worker, NULL); } } // 关闭线程池 void pool_shutdown() { int i; pool_shutdown = 1; pthread_mutex_lock(&queue_mutex); pthread_cond_broadcast(&queue_cond); pthread_mutex_unlock(&queue_mutex); for (i = 0; i < MAX_THREADS; i++) { pthread_join(worker_threads[i], NULL); } } // 测试函数 void print_number(void *arg) { int number = *((int *)arg); printf("Number: %d\n", number); } int main() { pool_init(); int i; for (i = 0; i < 100; i++) { int *number = malloc(sizeof(int)); *number = i; pool_add_task(print_number, (void *)number); } pool_shutdown(); return 0; } 这个线程池实现包括了添加任务到队列,工作线程从请求队列中获取任务并执行,还有线程池的初始化和关闭。你可以在任务函数中处理自己的逻辑,此处的示例是打印数字。注意,这只是一个简单的线程池实现,还有许多其他特性可以添加。你可以在GitHub上查找更多更完整的C语言线程池实现
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

鱼香Ross

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

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

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

打赏作者

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

抵扣说明:

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

余额充值