【源码剖析】threadpool —— 基于 pthread 实现的简单线程池

【学习DirectX12】渲染——第一节 Introduction 在DirectX 12里面,用于描述资源的唯一接口是ID3D12Resource。ID3D12Heap接口允许不同的内存映射技术,用于优化GPU内存。为了在DX12里更好地状态管理,使用pipeline state object(PSO)来描述不同的渲染和计算管线。也就是PSO结合了渲染管线中的input assembly(IA),vertex shader(VS),hull shader(HS),domain shader(DS),geometry shade... 阅读详情

线程池介绍

线程池可以说是项目中经常会用到的组件,在这里假设读者都有一定的多线程基础,如果没有的话不妨在这里进行了解:POSIX 多线程基础。

线程池是什么?我的简单理解是有一组预先派生的线程,然后有一个管理员来管理和调度这些线程,你只需不断把需要完成的任务交给他,他就会调度线程的资源来帮你完成。

那么管理员是怎么做的呢?一种简单的方式就是,管理员管理一个任务的队列,如果收到新的任务,就把任务加到队列尾。每个线程盯着队列,如果队列非空,就去队列头拿一个任务来处理(每个任务只能被一个线程拿到),处理完了就继续去队列取任务。如果没有任务了,线程就休眠,直到任务队列不为空。如果这个管理员更聪明一点,他可能会在没有任务或任务少的时候减少线程的数量,任务处理不过来的时候增加线程的数量,这样就实现了资源的动态管理。

那么任务是什么呢?以后台服务器为例,每一个用户的请求就是一个任务,线程不断的在请求队列里取出请求,完成后继续处理下一个请求。

简单图示为:
threadpool

线程池有一个好处就是减少线程创建和销毁的时间,在任务处理时间比较短的时候这个好处非常显著,可以提升任务处理的效率。

线程池实现

这里介绍的是线程池的一个简单实现,在创建的时候预先派生指定数量的线程,然后去任务队列取添加进来的任务进行处理就好。

作者说之后会添加更多特性,我们作为学习之后就以这个版本为准就好了。

项目主页:https://github.com/yangtingcheng/projectwithcomment/tree/master/threadpool

数据结构

主要有两个自定义的数据结构

threadpool_task_t

用于保存一个等待执行的任务。一个任务需要指明:要运行的对应函数及函数的参数。所以这里的 struct 里有函数指针和 void 指针。

typedef struct {
    void (*function)(void *);
    void *argument;
} threadpool_task_t;

thread_pool_t

一个线程池的结构。因为是 C 语言,所以这里任务队列是用数组,并维护队列头和队列尾来实现。

struct threadpool_t {
  pthread_mutex_t lock;     /* 互斥锁 */
  pthread_cond_t notify;    /* 条件变量 */
  pthread_t *threads;       /* 线程数组的起始指针 */
  threadpool_task_t *queue; /* 任务队列数组的起始指针 */
  int thread_count;         /* 线程数量 */
  int queue_size;           /* 任务队列长度 */
  int head;                 /* 当前任务队列头 */
  int tail;                 /* 当前任务队列尾 */
  int count;                /* 当前待运行的任务数 */
  int shutdown;             /* 线程池当前状态是否关闭 */
  int started;              /* 正在运行的线程数 */
};

对外接口

  • threadpool_t *threadpool_create(int thread_count, int queue_size, int flags); 创建线程池,用 thread_count 指定派生线程数,queue_size 指定任务队列长度,flags 为保留参数,未使用。
  • int threadpool_add(threadpool_t *pool, void (*routine)(void *),void *arg, int flags); 添加需要执行的任务。第二个参数为对应函数指针,第三个为对应函数参数。flags 未使用。
  • int threadpool_destroy(threadpool_t *pool, int flags); 销毁存在的线程池。flags 可以指定是立刻结束还是平和结束。立刻结束指不管任务队列是否为空,立刻结束。平和结束指等待任务队列的任务全部执行完后再结束,在这个过程中不可以添加新的任务。

内部辅助函数

  • static void *threadpool_thread(void *threadpool); 线程池每个线程所执行的函数。
  • int threadpool_free(threadpool_t *pool); 释放线程池所申请的内存资源。

线程池使用

编译

参考项目根目录下的 Makefile, 直接用 make 编译。

测试用例

项目提供了三个测试用例(见 threadpool/test/),我们可以以此来学习线程池的用法并测试是否正常工作。这里提供其中一个:

#define THREAD 32
#define QUEUE  256

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <assert.h>

#include "threadpool.h"

int tasks = 0, done = 0;
pthread_mutex_t lock;

void dummy_task(void *arg) {
    usleep(10000);
    pthread_mutex_lock(&lock);
    /* 记录成功完成的任务数 */
    done++;
    pthread_mutex_unlock(&lock);
}

int main(int argc, char **argv)
{
    threadpool_t *pool;

    /* 初始化互斥锁 */
    pthread_mutex_init(&lock, NULL);

    /* 断言线程池创建成功 */
    assert((pool = threadpool_create(THREAD, QUEUE, 0)) != NULL);
    fprintf(stderr, "Pool started with %d threads and "
            "queue size of %d\n", THREAD, QUEUE);

    /* 只要任务队列还没满,就一直添加 */
    while(threadpool_add(pool, &dummy_task, NULL, 0) == 0) {
        pthread_mutex_lock(&lock);
        tasks++;
        pthread_mutex_unlock(&lock);
    }

    fprintf(stderr, "Added %d tasks\n", tasks);

    /* 不断检查任务数是否完成一半以上,没有则继续休眠 */
    while((tasks / 2) > done) {
        usleep(10000);
    }
    /* 这时候销毁线程池,0 代表 immediate_shutdown */
    assert(threadpool_destroy(pool, 0) == 0);
    fprintf(stderr, "Did %d tasks\n", done);

    return 0;
}

源码注释

源码注释一并放在 github, 点我。

threadpool.h

/*
 * Copyright (c) 2013, Mathias Brossard <mathias@brossard.org>.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef _THREADPOOL_H_
#define _THREADPOOL_H_

#ifdef __cplusplus
/* 对于 C++ 编译器,指定用 C 的语法编译 */
extern "C" {
#endif

/**
 * @file threadpool.h
 * @brief Threadpool Header File
 */

 /**
 * Increase this constants at your own risk
 * Large values might slow down your system
 */
#define MAX_THREADS 64
#define MAX_QUEUE 65536

/* 简化变量定义 */
typedef struct threadpool_t threadpool_t;

/* 定义错误码 */
typedef enum {
    threadpool_invalid        = -1,
    threadpool_lock_failure   = -2,
    threadpool_queue_full     = -3,
    threadpool_shutdown       = -4,
    threadpool_thread_failure = -5
} threadpool_error_t;

typedef enum {
    threadpool_graceful       = 1
} threadpool_destroy_flags_t;

/* 以下是线程池三个对外 API */

/**
 * @function threadpool_create
 * @brief Creates a threadpool_t object.
 * @param thread_count Number of worker threads.
 * @param queue_size   Size of the queue.
 * @param flags        Unused parameter.
 * @return a newly created thread pool or NULL
 */
/**
 * 创建线程池,有 thread_count 个线程,容纳 queue_size 个的任务队列,flags 参数没有使用
 */
threadpool_t *threadpool_create(int thread_count, int queue_size, int flags);

/**
 * @function threadpool_add
 * @brief add a new task in the queue of a thread pool
 * @param pool     Thread pool to which add the task.
 * @param function Pointer to the function that will perform the task.
 * @param argument Argument to be passed to the function.
 * @param flags    Unused parameter.
 * @return 0 if all goes well, negative values in case of error (@see
 * threadpool_error_t for codes).
 */
/**
 *  添加任务到线程池, pool 为线程池指针,routine 为函数指针, arg 为函数参数, flags 未使用
 */
int threadpool_add(threadpool_t *pool, void (*routine)(void *),
                   void *arg, int flags);

/**
 * @function threadpool_destroy
 * @brief Stops and destroys a thread pool.
 * @param pool  Thread pool to destroy.
 * @param flags Flags for shutdown
 *
 * Known values for flags are 0 (default) and threadpool_graceful in
 * which case the thread pool doesn't accept any new tasks but
 * processes all pending tasks before shutdown.
 */
/**
 * 销毁线程池,flags 可以用来指定关闭的方式
 */
int threadpool_destroy(threadpool_t *pool, int flags);

#ifdef __cplusplus
}
#endif

#endif /* _THREADPOOL_H_ */

threadpool.c

/*
 * Copyright (c) 2013, Mathias Brossard <mathias@brossard.org>.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *  1. Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *  2. Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/**
 * @file threadpool.c
 * @brief Threadpool implementation file
 */

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

#include "threadpool.h"

/**
 * 线程池关闭的方式
 */
typedef enum {
    immediate_shutdown = 1,
    graceful_shutdown  = 2
} threadpool_shutdown_t;

/**
 *  @struct threadpool_task
 *  @brief the work struct
 *
 *  @var function Pointer to the function that will perform the task.
 *  @var argument Argument to be passed to the function.
 */
/**
 * 线程池一个任务的定义
 */

typedef struct {
    void (*function)(void *);
    void *argument;
} threadpool_task_t;

/**
 *  @struct threadpool
 *  @brief The threadpool struct
 *
 *  @var notify       Condition variable to notify worker threads.
 *  @var threads      Array containing worker threads ID.
 *  @var thread_count Number of threads
 *  @var queue        Array containing the task queue.
 *  @var queue_size   Size of the task queue.
 *  @var head         Index of the first element.
 *  @var tail         Index of the next element.
 *  @var count        Number of pending tasks
 *  @var shutdown     Flag indicating if the pool is shutting down
 *  @var started      Number of started threads
 */
/**
 * 线程池的结构定义
 *  @var lock         用于内部工作的互斥锁
 *  @var notify       线程间通知的条件变量
 *  @var threads      线程数组,这里用指针来表示,数组名 = 首元素指针
 *  @var thread_count 线程数量
 *  @var queue        存储任务的数组,即任务队列
 *  @var queue_size   任务队列大小
 *  @var head         任务队列中首个任务位置(注:任务队列中所有任务都是未开始运行的)
 *  @var tail         任务队列中最后一个任务的下一个位置(注:队列以数组存储,head 和 tail 指示队列位置)
 *  @var count        任务队列里的任务数量,即等待运行的任务数
 *  @var shutdown     表示线程池是否关闭
 *  @var started      开始的线程数
 */
struct threadpool_t {
  pthread_mutex_t lock;
  pthread_cond_t notify;
  pthread_t *threads;
  threadpool_task_t *queue;
  int thread_count;
  int queue_size;
  int head;
  int tail;
  int count;
  int shutdown;
  int started;
};

/**
 * @function void *threadpool_thread(void *threadpool)
 * @brief the worker thread
 * @param threadpool the pool which own the thread
 */
/**
 * 线程池里每个线程在跑的函数
 * 声明 static 应该只为了使函数只在本文件内有效
 */
static void *threadpool_thread(void *threadpool);

int threadpool_free(threadpool_t *pool);

threadpool_t *threadpool_create(int thread_count, int queue_size, int flags)
{
    if(thread_count <= 0 || thread_count > MAX_THREADS || queue_size <= 0 || queue_size > MAX_QUEUE) {
        return NULL;
    }

    threadpool_t *pool;
    int i;

    /* 申请内存创建内存池对象 */
    if((pool = (threadpool_t *)malloc(sizeof(threadpool_t))) == NULL) {
        goto err;
    }

    /* Initialize */
    pool->thread_count = 0;
    pool->queue_size = queue_size;
    pool->head = pool->tail = pool->count = 0;
    pool->shutdown = pool->started = 0;

    /* Allocate thread and task queue */
    /* 申请线程数组和任务队列所需的内存 */
    pool->threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_count);
    pool->queue = (threadpool_task_t *)malloc
        (sizeof(threadpool_task_t) * queue_size);

    /* Initialize mutex and conditional variable first */
    /* 初始化互斥锁和条件变量 */
    if((pthread_mutex_init(&(pool->lock), NULL) != 0) ||
       (pthread_cond_init(&(pool->notify), NULL) != 0) ||
       (pool->threads == NULL) ||
       (pool->queue == NULL)) {
        goto err;
    }

    /* Start worker threads */
    /* 创建指定数量的线程开始运行 */
    for(i = 0; i < thread_count; i++) {
        if(pthread_create(&(pool->threads[i]), NULL,
                          threadpool_thread, (void*)pool) != 0) {
            threadpool_destroy(pool, 0);
            return NULL;
        }
        pool->thread_count++;
        pool->started++;
    }

    return pool;

 err:
    if(pool) {
        threadpool_free(pool);
    }
    return NULL;
}

int threadpool_add(threadpool_t *pool, void (*function)(void *),
                   void *argument, int flags)
{
    int err = 0;
    int next;

    if(pool == NULL || function == NULL) {
        return threadpool_invalid;
    }

    /* 必须先取得互斥锁所有权 */
    if(pthread_mutex_lock(&(pool->lock)) != 0) {
        return threadpool_lock_failure;
    }

    /* 计算下一个可以存储 task 的位置 */
    next = pool->tail + 1;
    next = (next == pool->queue_size) ? 0 : next;

    do {
        /* Are we full ? */
        /* 检查是否任务队列满 */
        if(pool->count == pool->queue_size) {
            err = threadpool_queue_full;
            break;
        }

        /* Are we shutting down ? */
        /* 检查当前线程池状态是否关闭 */
        if(pool->shutdown) {
            err = threadpool_shutdown;
            break;
        }

        /* Add task to queue */
        /* 在 tail 的位置放置函数指针和参数,添加到任务队列 */
        pool->queue[pool->tail].function = function;
        pool->queue[pool->tail].argument = argument;
        /* 更新 tail 和 count */
        pool->tail = next;
        pool->count += 1;

        /* pthread_cond_broadcast */
        /*
         * 发出 signal,表示有 task 被添加进来了
         * 如果由因为任务队列空阻塞的线程,此时会有一个被唤醒
         * 如果没有则什么都不做
         */
        if(pthread_cond_signal(&(pool->notify)) != 0) {
            err = threadpool_lock_failure;
            break;
        }
        /*
         * 这里用的是 do { ... } while(0) 结构
         * 保证过程最多被执行一次,但在中间方便因为异常而跳出执行块
         */
    } while(0);

    /* 释放互斥锁资源 */
    if(pthread_mutex_unlock(&pool->lock) != 0) {
        err = threadpool_lock_failure;
    }

    return err;
}

int threadpool_destroy(threadpool_t *pool, int flags)
{
    int i, err = 0;

    if(pool == NULL) {
        return threadpool_invalid;
    }

    /* 取得互斥锁资源 */
    if(pthread_mutex_lock(&(pool->lock)) != 0) {
        return threadpool_lock_failure;
    }

    do {
        /* Already shutting down */
        /* 判断是否已在其他地方关闭 */
        if(pool->shutdown) {
            err = threadpool_shutdown;
            break;
        }

        /* 获取指定的关闭方式 */
        pool->shutdown = (flags & threadpool_graceful) ?
            graceful_shutdown : immediate_shutdown;

        /* Wake up all worker threads */
        /* 唤醒所有因条件变量阻塞的线程,并释放互斥锁 */
        if((pthread_cond_broadcast(&(pool->notify)) != 0) ||
           (pthread_mutex_unlock(&(pool->lock)) != 0)) {
            err = threadpool_lock_failure;
            break;
        }

        /* Join all worker thread */
        /* 等待所有线程结束 */
        for(i = 0; i < pool->thread_count; i++) {
            if(pthread_join(pool->threads[i], NULL) != 0) {
                err = threadpool_thread_failure;
            }
        }
        /* 同样是 do{...} while(0) 结构*/
    } while(0);

    /* Only if everything went well do we deallocate the pool */
    if(!err) {
        /* 释放内存资源 */
        threadpool_free(pool);
    }
    return err;
}

int threadpool_free(threadpool_t *pool)
{
    if(pool == NULL || pool->started > 0) {
        return -1;
    }

    /* Did we manage to allocate ? */
    /* 释放线程 任务队列 互斥锁 条件变量 线程池所占内存资源 */
    if(pool->threads) {
        free(pool->threads);
        free(pool->queue);

        /* Because we allocate pool->threads after initializing the
           mutex and condition variable, we're sure they're
           initialized. Let's lock the mutex just in case. */
        pthread_mutex_lock(&(pool->lock));
        pthread_mutex_destroy(&(pool->lock));
        pthread_cond_destroy(&(pool->notify));
    }
    free(pool);
    return 0;
}


static void *threadpool_thread(void *threadpool)
{
    threadpool_t *pool = (threadpool_t *)threadpool;
    threadpool_task_t task;

    for(;;) {
        /* Lock must be taken to wait on conditional variable */
        /* 取得互斥锁资源 */
        pthread_mutex_lock(&(pool->lock));

        /* Wait on condition variable, check for spurious wakeups.
           When returning from pthread_cond_wait(), we own the lock. */
        /* 用 while 是为了在唤醒时重新检查条件 */
        while((pool->count == 0) && (!pool->shutdown)) {
            /* 任务队列为空,且线程池没有关闭时阻塞在这里 */
            pthread_cond_wait(&(pool->notify), &(pool->lock));
        }

        /* 关闭的处理 */
        if((pool->shutdown == immediate_shutdown) ||
           ((pool->shutdown == graceful_shutdown) &&
            (pool->count == 0))) {
            break;
        }

        /* Grab our task */
        /* 取得任务队列的第一个任务 */
        task.function = pool->queue[pool->head].function;
        task.argument = pool->queue[pool->head].argument;
        /* 更新 head 和 count */
        pool->head += 1;
        pool->head = (pool->head == pool->queue_size) ? 0 : pool->head;
        pool->count -= 1;

        /* Unlock */
        /* 释放互斥锁 */
        pthread_mutex_unlock(&(pool->lock));

        /* Get to work */
        /* 开始运行任务 */
        (*(task.function))(task.argument);
        /* 这里一个任务运行结束 */
    }

    /* 线程将结束,更新运行线程数 */
    pool->started--;

    pthread_mutex_unlock(&(pool->lock));
    pthread_exit(NULL);
    return(NULL);
}
C++11单头文件线程池:原理、实现与生产环境实战指南 并发编程是现代软件开发的核心技术之一,旨在通过多线程并行执行任务来提升程序性能。其基本原理是创建多个执行流,共享进程资源,以充分利用多核CPU的计算能力。线程池作为并发编程的关键技术,通过预先创建并管理一组工作线程,避免了线程频繁创建与销毁的巨大开销,同时提供了统一的任务队列和调度机制,极大地简化了并发控制,减少了死锁和数据竞争的风险。这项技术的核心价值在于提升系统吞吐量、降低资源消耗并增强程序稳定性,广泛应用于服务器后端、数据处理、高并发网络服务等场景。本文聚焦于C++11标准库实现的单头文件线程池,深入 阅读详情

相关推荐

C++11轻量级Web服务器实现:从Reactor模式到线程池的实战解析

Web服务器是现代网络应用的核心基础设施,其核心原理在于高效处理并发连接与HTTP协议通信。通过I/O多路复用技术(如epoll)实现事件驱动,服务器能够以单线程监控大量连接,这是高并发架构的基石。结合线程池技术,将耗时的业务逻辑处理与高效的事件分发解耦,有效解决了阻塞与资源竞争问题,从而在工程实践中实现高性能与可扩展性。这种Reactor模式与线程池的组合,广泛应用于后端服务、API网关等需要处理海量并发的场景。本文以C++11实现的轻量级Web服务器为例,深入剖析其核心架构,涵盖事件分发、连接管理、HT

weixin_33674976的博客 378

【c++池技术】之线程池

【c++池技术】之线程池

distant_Rove666的博客 1355

C++高性能Web服务器TinyWebServer源码解析与并发模型实践

在Linux服务器开发中,I/O多路复用与并发模型是构建高性能网络服务的核心基础。epoll作为Linux下高效的I/O事件通知机制,通过水平触发(LT)与边沿触发(ET)两种模式管理海量连接,其本质是操作系统提供的事件驱动编程接口。结合线程池技术,可构建出Reactor与Proactor两种经典并发架构,前者将I/O操作交由工作线程处理,后者则由主线程完成数据读写,实现业务逻辑与I/O的解耦,从而大幅提升吞吐量与资源利用率。这些技术广泛应用于需要高并发的Web服务器、API网关及实时通信系统中。本文以Gi

weixin_30457551的博客 627

【操作系统-线程池】Pthread 线程池的设计及实现

Lab Week 15 实验报告 实验内容:设计实现一个线程池 (Thread Pool) 使用 Pthread API 管理线程。 利用回调函数作为线程的启动函数。 采用 pthread 信号量解决线程池分配的互斥问题。 讨论上述方案的技术可行性,尝试写一个设计报告。 在一个源代码文件内实现编码、完成编译、运行和用例测试。 I.线程池 线程池的提出,主要是为了解决: (1)频繁地为某一任务创建和销毁线程所引起的系统资源耗费问题; (2)无限制地为并发请求创建线程且系统对线程数量没有限制而引起的系统资源

MaxwellWong 1468

线程本质与实战:从CPU调度到JVM线程池深度解析

线程是并发编程的底层基石,其本质是操作系统调度的硬件映射实体,涉及CPU寄存器、缓存一致性(MESI协议)、JVM内存模型(JMM)及内核task_struct等多层协同。理解线程需超越语法糖(如async/await),回归物理执行单元视角:它拥有独立栈空间、受调度器管理、存在上下文切换开销,并因共享内存引发可见性与原子性问题。技术价值在于支撑高吞吐、低延迟服务——正确配置线程池可提升QPS 130%,规避RejectedExecutionException;精准使用volatile或synchroniz

baochuanying9531的博客 425

C++实战项目进阶:从零构建高性能HTTP服务器

在系统编程领域,网络服务器是理解I/O模型、并发编程和资源管理的核心实践。其基本原理在于通过操作系统提供的I/O多路复用机制(如epoll、kqueue),高效管理大量并发连接,避免为每个连接创建线程带来的巨大开销。这项技术的核心价值在于能够构建高并发、低延迟的网络服务,是互联网基础设施的基石,广泛应用于Web服务器、API网关、实时通信等场景。本文以构建一个简易HTTP服务器为例,深入剖析了**Reactor模式**与**线程池**的协同工作机制。通过实现事件循环、连接状态管理和动态缓冲区等关键模块,开发

weixin_30644369的博客 435

TinyWebServer项目小白逐行解析第四集——threadpool

线程(Thread)是操作系统能够进行运算调度的最小单位,它被包含在进程之中,是进程中的实际运作单位。一个进程可以包含多个线程,这些线程共享进程的资源,如内存空间、文件描述符等,但每个线程都有自己独立的执行栈和程序计数器,能够独立执行代码。线程可以并发执行,从而提高程序的执行效率,尤其在处理多任务或需要异步操作的场景中非常有用。pthread_t本质上是一个数据类型,用于唯一标识一个线程。

weixin_65339192的博客 791

C++高性能服务器开发实战:从Reactor模型到零拷贝优化

网络编程是构建分布式系统的基石,其核心在于高效管理海量并发连接。传统多线程模型因资源开销巨大而难以应对C10K问题,于是I/O多路复用技术应运而生。通过select、poll到epoll/kqueue的演进,系统能够用单个线程监控大量文件描述符的状态变化,这正是事件驱动架构的原理。这种技术价值在于极大提升了资源利用率,使单机承载数万并发连接成为可能,为高并发服务提供底层支撑。应用场景广泛,从Web服务器、实时通信到游戏后端均依赖于此。本文以热门的“30天C++服务器”项目为蓝本,深入剖析如何基于Reacto

weixin_34367257的博客 445

深入swtpm源码:核心组件架构与关键函数实现原理

swtpm是一个基于libtpms的软件TPM模拟器,提供多种前端接口实现。本文将深入剖析swtpm的核心架构设计、关键组件实现原理以及主要函数的工作机制,帮助您全面理解这个强大的TPM模拟器的工作原理。 ## 🔍 swtpm架构概览 swtpm采用了分层架构设计,主要分为以下几个核心层次: ### 1. 前端接口层 - **Socket接口**:支持TCP/IP和Unix域套接字通信 -

gitblog_00090的博客 814

Linux C/C++实战进阶:AI Infra、后端与音视频开发核心能力栈解析

这类教程最值得先看的不是它覆盖了多少方向,而是它能不能帮你把零散的知识点,串成能解决实际问题的工程能力。特别是对于工作1-5年、想从“会写代码”转向“能搞定项目”的程序员,或者应届生想快速补齐项目经验,核心不是学更多新名词,而是搞清楚从原理到上线的完整链条里,每一步到底在做什么、为什么这么做、以及出了问题怎么查。 下面我会围绕Linux C/C++开发,拆解几个主流方向(AI基础设施、后端、音视频)的实战进阶路径。重点不是罗列知识点,而是告诉你每个阶段该优先掌握什么、怎么验证、以及从学习到落地的关键跳板在哪

weixin_34198881的博客 415

pthreadpool:CC ++的可移植(POSIXWindowsEmscripten)线程池

pthreadpool pthreadpool是一种可移植且高效的线程池实现。 它提供了与#pragma omp parallel for类似的功能,但具有其他功能。 特征: C接口(与C ++兼容)。 1D-6D循环带有步长参数。 在用户指定或自动检测的线程数上运行。 进行工作窃取调度,以实现有效的工作平衡。 工作项的无等待同步。 与Linux(包括Android),macOS,iOS,Windows,Emscripten环境兼容。 100%单元测试覆盖率。 吞吐量和延迟微基准测试。 例子 下面的示例演示使用线程池并行添加两个数组: static void add_arrays ( struct array_addition_context* context, size_t i) { context-> sum [i] = context-> augend [i]

C++并发编程实战:从多线程基础到线程池架构设计

并发编程是现代软件开发中提升程序性能的核心技术,它通过多线程机制让程序能够同时处理多个任务,充分利用多核CPU的计算资源。其基本原理在于将任务分解为可并行执行的单元,通过线程调度实现高效处理。这项技术的核心价值在于显著提升高并发场景下的程序吞吐量和响应速度,尤其适用于网络服务器、游戏引擎、高频交易等对性能有极致要求的领域。在C++中,并发编程更接近底层,开发者需要深入理解线程生命周期管理、数据同步等关键概念,例如使用互斥锁(mutex)防止数据竞争,利用条件变量(condition_variable)实现线

weixin_34332905的博客 427

易语言-易语言Hp-Socket5.4.1高性能TCP/UDP通信组件

v5.4.1 更新: > 加入线程池公共组件: 1、加入 IHPThreadPool 线程池公共组件 2、IHPThreadPool 主要方法: 1) Start:启动线程池 2) Stop:关闭线程池 3) Submit:提交任务 4) AdjustThreadCount:调整线程池大小 > 其他更新: 1、代码优化 2、增加HPThreadPool例程 3、httpserver发送大文件增加和HPThreadPool结合,能判断断开。可以自行添加其它扩展协议(如:断点续传)。 > 升级说明: 1、HP-Socket v5.4.1 完全兼容 HP-Socket v5.3.2 版本,可以直接替换升级

TKeed 启示录:SIGPIPE 让服务器崩溃的真相与高性能 Web 服务器的 5 个避坑经验

TKeed 是一款基于 Reactor 模型的高性能 HTTP WebServer,用 C 语言实现,核心由 epoll + 非阻塞 I/O + 线程池构成。在压测过程中,它曾因为一个不起眼的 **SIGPIPE 信号**在测试结束后整个进程直接崩溃。这篇 TKeed 启示录带你还原真相,并总结 5 条高性能 Web 服务器开发中真实踩过的坑,帮你少走弯路。 ## TKeed 是什么? TKe

gitblog_00476的博客 711

如何实现MCGS与S7-200SMART PLC以太网多台通信控制?

第九步:(设备工具箱—设备管理—鼠标依次点击通用TCP/IP父设备—西门子_ Smart200到设备窗口里面去)数据类型:第0位(指PLC地址变量小数点后面的位数,例如我地址是M0.0,那么在数据类型应填写通道的第00位)第十步:(鼠标双击打开通用TCPIP父设备0--[通用TCP/IP父设备]进入通信配置)通道地址:0(指小数点前面起始字节的地址,例如我地址是M0.0,那么应在通道地填写0)。第七步:(选择通用TCP/IP父设备,点击新增,右侧选定设备就会自动添加进去。

u010670857的博客 6732

耶鲁大学《博弈论》课程——逆向归纳

耶鲁大学《博弈论》课程——逆向归纳

ZYLer_的博客 7887

【ggml系列】【第四篇】ggml_graph_compute 多线程计算引擎与算子分发源码深度解析

本文深入解析了ggml框架的核心多线程计算引擎设计。通过静态计算规划与内存预分配机制,ggml实现了极低同步开销和零动态内存频繁分配的高效计算。文章详细剖析了三大核心模块: 计算入口:通过ggml_graph_compute_with_ctx实现"先规划后执行"的惰性计算模式,依次完成计划生成、内存分配和计算执行。 静态规划:ggml_graph_plan通过遍历计算图,精准预估峰值内存需求并确定最优并行度,支持多种算子类型的特定内存计算,最终生成对齐缓存线的执行计划。 多线程调度:采用SPMD数据并行范式

A_cainiao_A 458

从零开始:使用COLMAP与OpenMVS构建高精度三维Mesh模型

本文为零基础新手提供了使用COLMAP与OpenMVS构建高精度三维Mesh模型的完整实战指南。详细介绍了从环境配置、数据采集黄金法则,到COLMAP稀疏与稠密重建、OpenMVS网格生成与纹理映射的每一步操作,并分享了关键的避坑技巧与参数调优建议,帮助读者从二维照片中成功重建出属于自己的三维模型。

metal的博客 512

.NET平台本质解析:从CLR、IL到跨平台演进

.NET是一个统一的开发者平台,其核心是公共语言运行时(CLR)与中间语言(IL)构成的托管执行模型。CLR提供内存管理、异常处理、跨语言互操作等底层能力,而IL作为平台无关的字节码,由JIT编译器按需转换为原生指令,实现高性能与可移植性的平衡。这一设计赋予.NET强类型安全、确定性垃圾回收和企业级稳定性,广泛应用于银行核心系统、政务平台及云原生微服务。结合.NET Standard的API契约机制与.NET 5+的统一平台演进,开发者得以在Windows、Linux、macOS间无缝迁移代码。本文深入CL

diaojin6880的博客 419

手把手教你用DLP4500投影仪玩转结构光3D扫描(附固件烧录与序列设置避坑指南)

本文详细解析了如何使用DLP4500投影仪搭建结构光3D扫描系统,涵盖硬件组装、固件烧录、图案生成与优化等全流程。重点解决了固件烧录失败、图像格式错误等常见问题,并提供了实用的避坑指南和进阶技巧,帮助读者快速掌握DLP4500在3D扫描中的应用。

weixin_42662293的博客 309

深入解析经典蓝牙连接:从HCI命令到LMP协议的完整流程

本文深入解析经典蓝牙连接的完整流程,从设备发现、寻呼建立物理链路,到安全配对与加密的每一步。通过对照HCI LOG与AIR LOG,详细拆解了HCI命令与LMP协议报文的对应关系,帮助开发者精准定位连接问题,掌握蓝牙调试的核心方法。

weixin_29260291的博客 470
上一篇: 【源码剖析】Webbench —— 简洁而优美的压力测试工具
下一篇: 网络编程之Select模式
PGEva
博客等级 码龄10年 78粉丝 129原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值