关于thread:C线程池

5次阅读

共计 6432 个字符,预计需要花费 17 分钟才能阅读完成。


title: C 线程池
categories:

  • [C++]
    tags:
  • [编程语言]
    date: 2021/06/28

<div align = ‘right’> 作者:hackett</div>

<div align = ‘right’> 微信公众号:加班猿 </div>

C 线程池

1、筹备工作

查看线程相干接口函数:

线程创立

int pthread_create(pthread_t thread, const pthread_attr_t attr,void (start_routine) (void ), void arg);

参数阐明:

1. 参数 thread 指向寄存新创建线程的线程 ID 的地址

2.attr 参数用于定制各种不同的线程属性,暂能够把它设置为 NULL,以创立默认属性的线程。

3.start_routine 是个函数指针,该函数返回类型是 void,同时形式参数也是 void。新创建的线程从 start_routine 函数的地址开始运行。该函数只有一个无类型指针参数 arg. 如果须要向 start_routine 函数传递的参数不止一个,那么须要把这些参数放到一个构造中,而后把这个构造的地址作为 arg 参数传入。

返回值:

线程创立胜利返回 0,失败返回其余数值

线程退出

void pthread_exit(void *retval);

参数阐明:

retval 是一个无类型指针,过程中的其余线程能够通过调用 pthread_join 函数拜访到这个指针。

线程期待

int pthread_join(pthread_t thread, void **retval);

参数阐明:

调用这个函数的线程将始终阻塞,直到指定的线程调用 pthread_exit. 如果对线程的返回值不感兴趣,能够把 retval 置为 NULL。在这种状况下,调用 pthread_join 函数将期待指定的线程终止,但并不取得线程的终止状态。

线程勾销

int pthread_cancel(pthread_t thread);

参数阐明:

thread 为线程的 id

设置线程的 cancle 信号

int pthread_setcancelstate(int state, int *oldstate);

PTHREAD_CANCEL_ENABLE:线程可勾销。这是所有新线程的默认勾销状态,包含初始线程。线程的可勾销类型决定了可勾销线程何时响应勾销申请。

PTHREAD_CANCEL_DISABLE:线程不可勾销。如果收到一个勾销申请,它将被阻塞,直到可勾销启用。

清理线程

void pthread_cleanup_push(void (*rtn)(void *), void *arg);

参数阐明:

void(*rtn)(void *): 线程清理函数

arg 传递的参数

激活所有期待线程

pthread_cond_broadcast(pthread_cond_t *cond);

查看互斥锁相干接口函数:

创立互斥锁

int pthread_mutex_init(pthread_mutex_t restrict mutex,const pthread_mutexattr_t restrict attr);

参数阐明:

1. 在应用互斥锁前,须要定义互斥锁(全局变量),定义互斥锁对象模式为:pthread_mutex_t lock;

2.mutex 是个指针,指向须要初始化的互斥锁;

3. 参数 attr 指定了新建互斥锁的属性。如果参数 attr 为 NULL,则应用默认的互斥锁属性,默认属性为疾速互斥锁。

销毁互斥锁

int pthread_mutex_destroy(pthread_mutex_t *mutex);

参数阐明:

mutex 为须要销毁的互斥锁;

上互斥锁

int pthread_mutex_lock(pthread_mutex_t *mutex);

参数阐明:

mutex 为须要加锁的互斥锁;

解互斥锁

int pthread_mutex_unlock(pthread_mutex_t *mute);

参数阐明:

mutex 为须要解锁的互斥锁;

查看条件变量相干接口函数:

条件变量是利用线程间共享的全局变量进行同步的一种机制,次要包含两个动作:一个线程期待 ” 条件变量的条件成立 ” 而挂起;另一个线程使 ” 条件成立 ”(给出条件成立信号)。为了避免竞争,条件变量的应用总是和一个互斥锁联合在一起。

初始化条件变量

int pthread_cond_init(pthread_cond_t cond, pthread_condattr_t cond_attr);

参数阐明:

1.cond 为初始化的条件变量,是一个指向构造 pthread_cond_t 的指针;

2.cond_attr 为 cond_attr 是一个指向构造 pthread_condattr_t 的指针;

销毁条件变量

int pthread_cond_destroy(pthread_cond_t *cond);

参数阐明:

cond 为销毁的条件变量;

期待条件变量成立

int pthread_cond_wait(pthread_cond_t cond, pthread_mutex_t mutex)

激活一个期待该条件变量的线程

int pthread_cond_signal(pthread_cond_t *__cond);

存在多个期待线程时按入队程序激活其中一个

2、创立数据结构

工作构造体

struct task
{void *(*task)(void *arg);    /* 工作须要执行的函数 */
    void *arg;                    /* 执行函数的参数 */
    struct task *next;            /* 下一个工作的地址 */
};

线程池构造体

typedef struct thread_pool
{
    pthread_mutex_t lock;
    pthread_cond_t  cond;
    struct task *task_list;    /* 链表构造,线程池中所有期待工作 */
    pthread_t *tids;        /* 寄存线程 id 的指针 */
    unsigned waiting_tasks; /* 以后期待的工作数 */
    unsigned active_threads;/* 线程池中线程数目 */
    bool shutdown;            /* 是否销毁线程池 */
}thread_pool;

3、线程池函数

初始化线程池

/*
 * @description: 初始化线程池
 * @param {thread_pool*} pool: 线程池构造体指针 {unsigned int} max_thread_num: 创立几个线程
 * @return: false 失败 true 胜利
 */
bool init_pool(thread_pool *pool, unsigned int threads_number)
{pthread_mutex_init(&pool->lock, NULL);    /* 初始化线程锁 */
    pthread_cond_init(&pool->cond, NULL);    /* 初始化条件变量 */

    pool->shutdown = false;                    
    pool->task_list = malloc(sizeof(struct task));
    pool->tids = malloc(sizeof(pthread_t) * MAX_ACTIVE_THREADS);

    if(pool->task_list == NULL || pool->tids == NULL)
    {perror("allocate memory error");
        return false;
    }

    pool->task_list->next = NULL;

    pool->waiting_tasks = 0;
    pool->active_threads = threads_number;

    int i;
    for(i=0; i<pool->active_threads; i++)
    {if(pthread_create(&((pool->tids)[i]), NULL,
                    routine, (void *)pool) != 0)
        {perror("create threads error");
            return false;
        }
    }
    return true;
}

向线程池增加工作

/*
 * @description: 向线程池增加工作
 * @param {thread_pool*} pool: 线程池构造体指针 {void *(void *arg)} (*task): 线程的回调函数 {void *} arg: 传入的参数
 * @return: false 失败 true 胜利
 */
bool add_task(thread_pool *pool,
            void *(*task)(void *arg), void *arg)
{struct task *new_task = malloc(sizeof(struct task));
    if(new_task == NULL)
    {perror("allocate memory error");
        return false;
    }
    new_task->task = task;
    new_task->arg = arg;
    new_task->next = NULL;


    pthread_mutex_lock(&pool->lock);
    if(pool->waiting_tasks >= MAX_WAITING_TASKS)
    {pthread_mutex_unlock(&pool->lock);

        fprintf(stderr, "too many tasks.\n");
        free(new_task);

        return false;
    }
    
    struct task *tmp = pool->task_list;
    while(tmp->next != NULL)
        tmp = tmp->next;

    tmp->next = new_task;
    pool->waiting_tasks++;


    pthread_mutex_unlock(&pool->lock);
    pthread_cond_signal(&pool->cond);

    return true;
}

向线程池增加线程

/*
 * @description: 向线程池增加线程
 * @param {thread_pool*} pool: 线程池构造体指针 {unsigned int} additional_threads: 增加的线程数
 * @return: 返回胜利的线程数
 */
int add_thread(thread_pool *pool, unsigned int additional_threads)
{if(additional_threads == 0)
        return 0;

    unsigned int total_threads =
             pool->active_threads + additional_threads;

    int i, actual_increment = 0;
    for(i = pool->active_threads;
        i < total_threads && i < MAX_ACTIVE_THREADS;
        i++)
    {if(pthread_create(&((pool->tids)[i]),
                NULL, routine, (void *)pool) != 0)
        {perror("add threads error");

            if(actual_increment == 0)
                return -1;

            break;
        }
        actual_increment++; 
    }

    pool->active_threads += actual_increment;
    return actual_increment;
}

线程的回调处理函数

/*
 * @description: 回调处理函数
 * @param  {void *} arg: 传入的参数
 * @return: 无
 */
void handler(void *arg)
{pthread_mutex_unlock((pthread_mutex_t *)arg);
}
/*
 * @description: 线程的回调处理函数
 * @param  {void *} arg: 传入的参数
 * @return: 无
 */
void *routine(void *arg)
{thread_pool *pool = (thread_pool *)arg;
    struct task *p;

    while(1)
    {pthread_cleanup_push(handler, (void *)&pool->lock);
        pthread_mutex_lock(&pool->lock);


        while(pool->waiting_tasks == 0 && !pool->shutdown)
        {pthread_cond_wait(&pool->cond, &pool->lock);
        }


        if(pool->waiting_tasks == 0 && pool->shutdown == true)
        {pthread_mutex_unlock(&pool->lock);
            pthread_exit(NULL);
        }


        p = pool->task_list->next;
        pool->task_list->next = p->next;
        pool->waiting_tasks--;


        pthread_mutex_unlock(&pool->lock);
        pthread_cleanup_pop(0);


        pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
        (p->task)(p->arg);
        pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

        free(p);
    }

    pthread_exit(NULL);
}

线程池里勾销线程

/*
 * @description: 线程池里勾销线程
 * @param {thread_pool*} pool: 线程池构造体指针 {nsigned int} removing_threads: 勾销的线程数
 * @return: 失败返回 -1
 */
int remove_thread(thread_pool *pool, unsigned int removing_threads)
{if(removing_threads == 0)
        return pool->active_threads;

    int remain_threads = pool->active_threads - removing_threads;
    remain_threads = remain_threads>0 ? remain_threads:1;

    int i;
    for(i=pool->active_threads-1; i>remain_threads-1; i--)
    {errno = pthread_cancel(pool->tids[i]);
        if(errno != 0)
            break;
    }

    if(i == pool->active_threads-1)
        return -1;
    else
    {
        pool->active_threads = i+1;
        return i+1;
    }
}

销毁线程池

/*
 * @description: 销毁线程池
 * @param {thread_pool*} pool: 线程池构造体指针
 * @return: 胜利返回 true
 */
bool destroy_pool(thread_pool *pool)
{

    pool->shutdown = true;
    pthread_cond_broadcast(&pool->cond);

    int i;
    for(i=0; i<pool->active_threads; i++)
    {errno = pthread_join(pool->tids[i], NULL);
        if(errno != 0)
        {printf("join tids[%d] error: %s\n",
                    i, strerror(errno));
        }
        else
            printf("[%u] is joined\n", (unsigned)pool->tids[i]);
        
    }

    free(pool->task_list);
    free(pool->tids);
    free(pool);

    return true;
}

4、残缺代码

因为篇幅较长就不贴出来 代码放百度云,须要的在微信公众号回复【线程】即可获取链接下载

应用:Linux 下进入文件夹执行 make 生成可执行文件 test 执行即可

如果你感觉文章还不错,能够给个 ”三连

我是 加班猿,咱们下期见

正文完
 0