C++单例模式实现线程池的示例代码

 更新时间:2023年04月20日 16:38:17   作者:Michael_Good  
这篇文章主要为大家详细介绍了如何利用C++单例模式简单实现一个线程池,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起了解一下

C语言单例模式实现线程池。

该代码中,使用了单例模式来创建线程池对象,保证了整个程序中只有一个线程池对象。

线程池中包含了任务队列、工作线程数组、互斥锁、条件变量等成员,通过这些成员来实现任务的提交和执行。

在主函数中,提交了10个任务,每个任务都是一个简单的打印数字的函数,最后等待所有任务执行完毕后销毁线程池。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define THREAD_POOL_SIZE 5

// 任务结构体
typedef struct {
    void (*task)(void*);
    void* arg;
} Task;

// 线程池结构体
typedef struct {
    Task* tasks; // 任务队列
    int size; // 任务队列大小
    int head; // 任务队列头指针
    int tail; // 任务队列尾指针
    int count; // 任务队列中任务数量
    pthread_mutex_t lock; // 互斥锁
    pthread_cond_t not_empty; // 非空条件变量
    pthread_cond_t not_full; // 非满条件变量
    int shutdown; // 线程池是否关闭
    pthread_t* threads; // 工作线程数组
    int thread_count; // 工作线程数量
} ThreadPool;

// 线程池单例结构体
typedef struct {
    ThreadPool* pool; // 线程池指针
} ThreadPoolSingleton;

static ThreadPoolSingleton* instance = NULL; // 线程池单例对象指针

// 工作线程函数
void* worker(void* arg) {
    ThreadPool* pool = (ThreadPool*)arg;
    while (1) {
        pthread_mutex_lock(&pool->lock);
        while (pool->count == 0 && !pool->shutdown) {
            pthread_cond_wait(&pool->not_empty, &pool->lock);
        }
        if (pool->count == 0 && pool->shutdown) {
            pthread_mutex_unlock(&pool->lock);
            pthread_exit(NULL);
        }
        Task task = pool->tasks[pool->head];
        pool->head = (pool->head + 1) % pool->size;
        pool->count--;
        pthread_cond_signal(&pool->not_full);
        pthread_mutex_unlock(&pool->lock);
        task.task(task.arg);
    }
    return NULL;
}

// 创建线程池函数
ThreadPool* create_thread_pool(int thread_count, int queue_size) {
    ThreadPool* pool = (ThreadPool*)malloc(sizeof(ThreadPool));
    pool->tasks = (Task*)malloc(sizeof(Task) * queue_size);
    pool->size = queue_size;
    pool->head = 0;
    pool->tail = 0;
    pool->count = 0;
    pthread_mutex_init(&pool->lock, NULL);
    pthread_cond_init(&pool->not_empty, NULL);
    pthread_cond_init(&pool->not_full, NULL);
    pool->shutdown = 0;
    pool->threads = (pthread_t*)malloc(sizeof(pthread_t) * thread_count);
    pool->thread_count = thread_count;
    for (int i = 0; i < thread_count; i++) {
        pthread_create(&pool->threads[i], NULL, worker, pool);
    }
    return pool;
}

// 销毁线程池函数
void destroy_thread_pool(ThreadPool* pool) {
    pthread_mutex_lock(&pool->lock);
    pool->shutdown = 1;
    pthread_mutex_unlock(&pool->lock);
    pthread_cond_broadcast(&pool->not_empty);
    for (int i = 0; i < pool->thread_count; i++) {
        pthread_join(pool->threads[i], NULL);
    }
    free(pool->threads);
    free(pool->tasks);
    pthread_mutex_destroy(&pool->lock);
    pthread_cond_destroy(&pool->not_empty);
    pthread_cond_destroy(&pool->not_full);
    free(pool);
}

// 提交任务函数
void submit_task(ThreadPool* pool, void (*task)(void*), void* arg) {
    pthread_mutex_lock(&pool->lock);
    while (pool->count == pool->size && !pool->shutdown) {
        pthread_cond_wait(&pool->not_full, &pool->lock);
    }
    if (pool->shutdown) {
        pthread_mutex_unlock(&pool->lock);
        return;
    }
    pool->tasks[pool->tail].task = task;
    pool->tasks[pool->tail].arg = arg;
    pool->tail = (pool->tail + 1) % pool->size;
    pool->count++;
    pthread_cond_signal(&pool->not_empty);
    pthread_mutex_unlock(&pool->lock);
}

// 任务函数
void task_func(void* arg) {
    int* num = (int*)arg;
    printf("task %d is running\n", *num);
    free(num);
}

// 任务包装函数
void* task_wrapper(void* arg) {
    TaskWrapper* wrapper = (TaskWrapper*)arg;
    submit_task(wrapper->pool, wrapper->task, wrapper->arg);
    free(wrapper);
    return NULL;
}

init_instance() {
	instance = (ThreadPoolSingleton*)malloc(sizeof(ThreadPoolSingleton));
	instance->pool = create_thread_pool(THREAD_POOL_SIZE, THREAD_POOL_SIZE);
}
// 获取线程池单例对象函数
ThreadPool* get_thread_pool_instance() {
    return instance->pool;
}

int main() {
	init_instance();	/* 程序一开始,就必须执行。不然,与懒汉式无较大差异 */
    ThreadPool* pool = get_thread_pool_instance(); // 获取线程池单例对象
    for (int i = 0; i < 10; i++) {
        int* num = (int*)malloc(sizeof(int));
        *num = i;
        TaskWrapper* wrapper = (TaskWrapper*)malloc(sizeof(TaskWrapper));
        wrapper->pool = pool
		wrapper->task = task_func;
		wrapper->arg = num;
		pthread_t tid;
		pthread_create(&tid, NULL, task_wrapper, wrapper); // 提交任务
	}
	sleep(1); // 等待所有任务执行完毕
	destroy_thread_pool(pool); // 销毁线程池
	return 0;
}

/*
该示例代码中,使用了单例模式来创建线程池对象,保证了整个程序中只有一个线程池对象。
线程池中包含了任务队列、工作线程数组、互斥锁、条件变量等成员,通过这些成员来实现任务的提交和执行。
在主函数中,提交了10个任务,每个任务都是一个简单的打印数字的函数,最后等待所有任务执行完毕后销毁线程池。
*/

到此这篇关于C++单例模式实现线程池的示例代码的文章就介绍到这了,更多相关C++单例模式实现线程池内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 浅析C++中strlen函数的使用与模拟实现strlen的方法

    浅析C++中strlen函数的使用与模拟实现strlen的方法

    这篇文章主要介绍了strlen函数的使用与模拟实现strlen的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • 在C语言编程中设置和获取代码组数的方法

    在C语言编程中设置和获取代码组数的方法

    这篇文章主要介绍了在C语言编程中设置和获取代码组数的方法,分别为setgroups()函数和getgroups()函数的使用,需要的朋友可以参考下
    2015-08-08
  • C语言中数组的一些基本知识小结

    C语言中数组的一些基本知识小结

    这篇文章主要介绍了C语言中数组的一些基本知识小结,其中重点是对于数组的内存分配相关方面的知识整理,需要的朋友可以参考下
    2016-04-04
  • google c++程序测试框架googletest使用教程详解

    google c++程序测试框架googletest使用教程详解

    &#8203;GoogleTest 是 Google 的 C++ 测试和模拟框架,可以帮助程序员测试C++程序的结果预期,这篇文章主要介绍了google c++程序测试框架googletest使用教程,需要的朋友可以参考下
    2021-08-08
  • 老生常谈C++ explicit关键字

    老生常谈C++ explicit关键字

    这篇文章主要介绍了C++ explicit关键字,explicit关键字只需用于类内的单参数构造函数前面,由于无参数的构造函数和多参数的构造函数总是显式调用,这种情况在构造函数前加explicit无意义,需要的朋友可以参考下
    2023-03-03
  • [c++]变量声明与定义的规则详解

    [c++]变量声明与定义的规则详解

    这篇文章主要介绍了[c++]变量声明与定义的规则详解,对于学习c++的朋友来说这是一个很细腻的文章,代码完整,需要的朋友可以参考下
    2021-04-04
  • 基于QT5实现一个时钟桌面

    基于QT5实现一个时钟桌面

    这篇文章主要介绍了利用QT5实现的一个时钟桌面,文中的示例代码讲解详细,对我们学习或工作有一定的帮助,感兴趣的小伙伴可以了解一下
    2022-01-01
  • C/C++ Qt StatusBar底部状态栏应用教程

    C/C++ Qt StatusBar底部状态栏应用教程

    Qt窗体中默认会附加一个QstatusBar组件,状态栏组件位于主窗体的最下方,其作用是提供一个工具提示功能。本文主要介绍了StatusBar底部状态栏的应用教程,需要的同学可以学习一下
    2021-12-12
  • C语言中const,volatile,restrict的用法总结

    C语言中const,volatile,restrict的用法总结

    以下是对C语言中const,volatile,restrict的用法进行了详细的总结介绍,需要的朋友可以过来参考下
    2013-10-10
  • C语言字符函数与字符串函数的实现示例

    C语言字符函数与字符串函数的实现示例

    C语言标准库中的<ctype.h>和<string.h>头文件分别提供了丰富的字符处理和字符串处理函数,本文就来介绍一下C语言字符函数与字符串函数的实现示例,感兴趣的可以了解一下
    2024-11-11

最新评论