消息分類 ==> 線程創(chuàng)建 ==> 傳遞消息到子線程 ==> 線程分離 ==> 在子線程中執(zhí)行任務(wù) ==> 任務(wù)結(jié)束退出; 對(duì)大多數(shù)小型局域網(wǎng)的通信來說,上述方法足夠滿足需求;但當(dāng)我們的通信范圍擴(kuò)大到廣域網(wǎng)或大型局域網(wǎng)通信中時(shí),我們將面臨大量消息頻繁請(qǐng)求服務(wù)器;在這種情況下,創(chuàng)" />
0
  • 聊天消息
  • 系統(tǒng)消息
  • 評(píng)論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會(huì)員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識(shí)你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

如何用C語言實(shí)現(xiàn)線程池

科技綠洲 ? 來源:Linux開發(fā)架構(gòu)之路 ? 作者:Linux開發(fā)架構(gòu)之路 ? 2023-11-13 10:41 ? 次閱讀

線程池是一種多線程處理形式,大多用于高并發(fā)服務(wù)器上,它能合理有效的利用高并發(fā)服務(wù)器上的線程資源;線程與進(jìn)程用于處理各項(xiàng)分支子功能,我們通常的操作是:接收消息 ==> 消息分類 ==> 線程創(chuàng)建 ==> 傳遞消息到子線程 ==> 線程分離 ==> 在子線程中執(zhí)行任務(wù) ==> 任務(wù)結(jié)束退出;

對(duì)大多數(shù)小型局域網(wǎng)的通信來說,上述方法足夠滿足需求;但當(dāng)我們的通信范圍擴(kuò)大到廣域網(wǎng)或大型局域網(wǎng)通信中時(shí),我們將面臨大量消息頻繁請(qǐng)求服務(wù)器;在這種情況下,創(chuàng)建與銷毀線程都已經(jīng)成為一種奢侈的開銷,特別對(duì)于嵌入式服務(wù)器來說更應(yīng)保證內(nèi)存資源的合理利用;

因此,線程池技術(shù)應(yīng)運(yùn)而生;線程池允許一個(gè)線程可以多次復(fù)用,且每次復(fù)用的線程內(nèi)部的消息處理可以不相同,將創(chuàng)建與銷毀的開銷省去而不必來一個(gè)請(qǐng)求開一個(gè)線程;

結(jié)構(gòu)講解:

線程池是一個(gè)抽象的概念,其內(nèi)部由任務(wù)隊(duì)列,一堆線程,管理者線程組成;

圖片

我們將以上圖為例,實(shí)現(xiàn)一個(gè)最基礎(chǔ)的線程池,接下來將分部分依次講解;講解順序?yàn)椋?.線程池總體結(jié)構(gòu) 2.線程數(shù)組 3.任務(wù)隊(duì)列 4.管理者線程 5.使用線程池接口的例子

一、線程池總體結(jié)構(gòu)

這里講解線程池在邏輯上的結(jié)構(gòu)體;看下方代碼,該結(jié)構(gòu)體threadpool_t中包含線程池狀態(tài)信息,任務(wù)隊(duì)列信息以及多線程操作中的互斥鎖;在任務(wù)結(jié)構(gòu)體中包含了一個(gè)可以放置多種不同任務(wù)函數(shù)的函數(shù)指針,一個(gè)傳入該任務(wù)函數(shù)的void*類型的參數(shù);

注意:在使用時(shí)需要將你的消息分類處理函數(shù)裝入任務(wù)的(*function);然后放置到任務(wù)隊(duì)列并通知空閑線程;

線程池狀態(tài)信息:描述當(dāng)前線程池的基本信息,如是否開啟、最小線程數(shù)、最大線程數(shù)、存活線程數(shù)、忙線程數(shù)、待銷毀線程數(shù)等… …

任務(wù)隊(duì)列信息:描述當(dāng)前任務(wù)隊(duì)列基本信息,如最大任務(wù)數(shù)、隊(duì)列不為滿條件變量、隊(duì)列不為空條件變量等… …

多線程互斥鎖:保證在同一時(shí)間點(diǎn)上只有一個(gè)線程在任務(wù)隊(duì)列中取任務(wù)并修改任務(wù)隊(duì)列信息、修改線程池信息;

函數(shù)指針:在打包消息階段,將分類后的消息處理函數(shù)放在(*function);

void*類型參數(shù):用于傳遞消息處理函數(shù)需要的信息;

/ 任務(wù) /

typedef struct {

void *(*function)(void *);

void *arg;

} threadpool_task_t;

/ 線程池管理 /

struct threadpool_t{

pthread_mutex_t lock; /* 鎖住整個(gè)結(jié)構(gòu)體 */

pthread_mutex_t thread_counter; /* 用于使用忙線程數(shù)時(shí)的鎖 */

pthread_cond_t queue_not_full; /* 條件變量,任務(wù)隊(duì)列不為滿 */

pthread_cond_t queue_not_empty; /* 任務(wù)隊(duì)列不為空 */

pthread_t threads; / 存放線程的tid,實(shí)際上就是管理了線 數(shù)組 */

pthread_t admin_tid; /* 管理者線程tid */

threadpool_task_t task_queue; / 任務(wù)隊(duì)列 */

/ 線程池信息 /

int min_thr_num; /* 線程池中最小線程數(shù) */

int max_thr_num; /* 線程池中最大線程數(shù) */

int live_thr_num; /* 線程池中存活的線程數(shù) */

int busy_thr_num; /* 忙線程,正在工作的線程 */

int wait_exit_thr_num; /* 需要銷毀的線程數(shù) */

/ 任務(wù)隊(duì)列信息 /

int queue_front; /* 隊(duì)頭 */

int queue_rear; /* 隊(duì)尾 */

int queue_size;

/* 存在的任務(wù)數(shù) */

int queue_max_size; /* 隊(duì)列能容納的最大任務(wù)數(shù) */

/ 線程池狀態(tài) /

int shutdown; /* true為關(guān)閉 */

};

/ 創(chuàng)建線程池 /

threadpool_t *

threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size)

{ /* 最小線程數(shù) 最大線程數(shù) 最大任務(wù)數(shù)*/

int i;

threadpool_t *pool = NULL;

do

{

/* 線程池空間開辟 */

if ((pool=(threadpool_t *)malloc(sizeof(threadpool_t))) == NULL)

{

printf("malloc threadpool false; n");

break;

}

/ 信息初始化 /

pool->min_thr_num = min_thr_num;

pool->max_thr_num = max_thr_num;

pool->busy_thr_num = 0;

pool->live_thr_num = min_thr_num;

pool->wait_exit_thr_num = 0;

pool->queue_front = 0;

pool->queue_rear = 0;

pool->queue_size = 0;

pool->queue_max_size = queue_max_size;

pool->shutdown = false;

/* 根據(jù)最大線程數(shù),給工作線程數(shù)組開空間,清0 */

pool->threads = (pthread_t *)malloc(sizeof(pthread_t)*max_thr_num);

if (pool->threads == NULL)

{

printf("malloc threads false;n");

break;

}

memset(pool->threads, 0, sizeof(pthread_t)*max_thr_num);

/* 隊(duì)列開空間 */

pool->task_queue =

(threadpool_task_t *)malloc(sizeof(threadpool_task_t)*queue_max_size);

if (pool->task_queue == NULL)

{

printf("malloc task queue false;n");

break;

}

/* 初始化互斥鎖和條件變量 */

if ( pthread_mutex_init(&(pool->lock), NULL) != 0 ||

pthread_mutex_init(&(pool->thread_counter), NULL) !=0 ||

pthread_cond_init(&(pool->queue_not_empty), NULL) !=0 ||

pthread_cond_init(&(pool->queue_not_full), NULL) !=0)

{

printf("init lock or cond false;n");

break;

}

/* 啟動(dòng)min_thr_num個(gè)工作線程 */

for (i=0; i

{

/* pool指向當(dāng)前線程池 threadpool_thread函數(shù)在后面講解 */

pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool);

printf("start thread 0x%x... n", (unsigned int)pool->threads[i]);

}

/* 管理者線程 admin_thread函數(shù)在后面講解 */

pthread_create(&(pool->admin_tid), NULL, admin_thread, (void *)pool);

return pool;

} while(0);

/* 釋放pool的空間 */

threadpool_free(pool);

return NULL;

}

二、線程數(shù)組

線程數(shù)組實(shí)際上是在線程池初始化時(shí)開辟的一段存放一堆線程tid的空間,在邏輯上形成一個(gè)池,里面放置著提前創(chuàng)建的線程;這段空間中包含了正在工作的線程,等待工作的線程(空閑線程),等待被銷毀的線程,申明但沒有初始化的線程空間;

圖片

/ 工作線程 /

void *

threadpool_thread(void *threadpool)

{

threadpool_t *pool = (threadpool_t *)threadpool;

threadpool_task_t task;

while (true)

{

pthread_mutex_lock(&(pool->lock));

/* 無任務(wù)則阻塞在 “任務(wù)隊(duì)列不為空” 上,有任務(wù)則跳出 */

while ((pool->queue_size == 0) && (!pool->shutdown))

{

printf("thread 0x%x is waiting n", (unsigned int)pthread_self());

pthread_cond_wait(&(pool->queue_not_empty), &(pool->lock));

/* 判斷是否需要清除線程,自殺功能 */

if (pool->wait_exit_thr_num > 0)

{

pool->wait_exit_thr_num--;

/* 判斷線程池中的線程數(shù)是否大于最小線程數(shù),是則結(jié)束當(dāng)前線程 */

if (pool->live_thr_num > pool->min_thr_num)

{

printf("thread 0x%x is exiting n", (unsigned int)pthread_self());

pool->live_thr_num--;

pthread_mutex_unlock(&(pool->lock));

pthread_exit(NULL);//結(jié)束線程

}

}

}

/* 線程池開關(guān)狀態(tài) */

if (pool->shutdown) //關(guān)閉線程池

{

pthread_mutex_unlock(&(pool->lock));

printf("thread 0x%x is exiting n", (unsigned int)pthread_self());

pthread_exit(NULL); //線程自己結(jié)束自己

}

//否則該線程可以拿出任務(wù)

task.function = pool->task_queue[pool->queue_front].function; //出隊(duì)操作

task.arg = pool->task_queue[pool->queue_front].arg;

pool->queue_front = (pool->queue_front + 1) % pool->queue_max_size; //環(huán)型結(jié)構(gòu)

pool->queue_size--;

//通知可以添加新任務(wù)

pthread_cond_broadcast(&(pool->queue_not_full));

//釋放線程鎖

pthread_mutex_unlock(&(pool->lock));

//執(zhí)行剛才取出的任務(wù)

printf("thread 0x%x start working n", (unsigned int)pthread_self());

pthread_mutex_lock(&(pool->thread_counter)); //鎖住忙線程變量

pool->busy_thr_num++;

pthread_mutex_unlock(&(pool->thread_counter));

(*(task.function))(task.arg); //執(zhí)行任務(wù)

//任務(wù)結(jié)束處理

printf("thread 0x%x end working n", (unsigned int)pthread_self());

pthread_mutex_lock(&(pool->thread_counter));

pool->busy_thr_num--;

pthread_mutex_unlock(&(pool->thread_counter));

}

pthread_exit(NULL);

}

三、任務(wù)隊(duì)列

任務(wù)隊(duì)列的存在形式與線程數(shù)組相似;在線程池初始化時(shí)根據(jù)傳入的最大任務(wù)數(shù)開辟空間;當(dāng)服務(wù)器前方后請(qǐng)求到來后,分類并打包消息成為任務(wù),將任務(wù)放入任務(wù)隊(duì)列并通知空閑線程來?。徊煌幵谟谌蝿?wù)隊(duì)列有明顯的先后順序,先進(jìn)先出;而線程數(shù)組中的線程則是一個(gè)競爭關(guān)系去拿到互斥鎖爭取任務(wù);

圖片

/ 向線程池的任務(wù)隊(duì)列中添加一個(gè)任務(wù) /

int

threadpool_add_task(threadpool_t *pool, void *(*function)(void *arg), void *arg)

{

pthread_mutex_lock(&(pool->lock));

/ 如果隊(duì)列滿了,調(diào)用wait阻塞 /

while ((pool->queue_size == pool->queue_max_size) && (!pool->shutdown))

pthread_cond_wait(&(pool->queue_not_full), &(pool->lock));

/ 如果線程池處于關(guān)閉狀態(tài) /

if (pool->shutdown)

{

pthread_mutex_unlock(&(pool->lock));

return -1;

}

/ 清空工作線程的回調(diào)函數(shù)的參數(shù)arg /

if (pool->task_queue[pool->queue_rear].arg != NULL)

{

free(pool->task_queue[pool->queue_rear].arg);

pool->task_queue[pool->queue_rear].arg = NULL;

}

/ 添加任務(wù)到任務(wù)隊(duì)列 /

pool->task_queue[pool->queue_rear].function = function;

pool->task_queue[pool->queue_rear].arg = arg;

pool->queue_rear = (pool->queue_rear + 1) % pool->queue_max_size; /* 邏輯環(huán) */

pool->queue_size++;

/ 添加完任務(wù)后,隊(duì)列就不為空了,喚醒線程池中的一個(gè)線程 /

pthread_cond_signal(&(pool->queue_not_empty));

pthread_mutex_unlock(&(pool->lock));

return 0;

}

四、管理者線程

作為線程池的管理者,該線程的主要功能包括:檢查線程池內(nèi)線程的存活狀態(tài),工作狀態(tài);負(fù)責(zé)根據(jù)服務(wù)器當(dāng)前的請(qǐng)求狀態(tài)去動(dòng)態(tài)的增加或刪除線程,保證線程池中的線程數(shù)量維持在一個(gè)合理高效的平衡上;

說到底,它就是一個(gè)單獨(dú)的線程,定時(shí)的去檢查,根據(jù)我們的一個(gè)維持平衡算法去增刪線程;

/ 管理線程 /

void *

admin_thread(void *threadpool)

{

int i;

threadpool_t *pool = (threadpool_t *)threadpool;

while (!pool->shutdown)

{

printf("admin -----------------n");

sleep(DEFAULT_TIME); / 隔一段時(shí)間再管理 /

pthread_mutex_lock(&(pool->lock)); / 加鎖 /

int queue_size = pool->queue_size; / 任務(wù)數(shù) /

int live_thr_num = pool->live_thr_num; / 存活的線程數(shù) /

pthread_mutex_unlock(&(pool->lock)); / 解鎖 /

pthread_mutex_lock(&(pool->thread_counter));

int busy_thr_num = pool->busy_thr_num; / 忙線程數(shù) /

pthread_mutex_unlock(&(pool->thread_counter));

printf("admin busy live -%d--%d-n", busy_thr_num, live_thr_num);

/ 創(chuàng)建新線程 實(shí)際任務(wù)數(shù)量大于 最小正在等待的任務(wù)數(shù)量,存活線程數(shù)小于最大線程數(shù) /

if (queue_size >= MIN_WAIT_TASK_NUM && live_thr_num <= pool->max_thr_num)

{

printf("admin add-----------n");

pthread_mutex_lock(&(pool->lock));

int add=0;

/ 一次增加 DEFAULT_THREAD_NUM 個(gè)線程 /

for (i=0; imax_thr_num && add

&& pool->live_thr_num < pool->max_thr_num; i++)

{

if (pool->threads[i] == 0 || !is_thread_alive(pool->threads[i]))

{

pthread_create(&(pool->threads[i]), NULL, threadpool_thread, (void *)pool);

add++;

pool->live_thr_num++;

printf("new thread -----------------------n");

}

}

pthread_mutex_unlock(&(pool->lock));

}

/ 銷毀多余的線程 忙線程x2 都小于 存活線程,并且存活的大于最小線程數(shù) /

if ((busy_thr_num*2) < live_thr_num && live_thr_num > pool->min_thr_num)

{

// printf("admin busy --%d--%d----n", busy_thr_num, live_thr_num);

/ 一次銷毀DEFAULT_THREAD_NUM個(gè)線程 /

pthread_mutex_lock(&(pool->lock));

pool->wait_exit_thr_num = DEFAULT_THREAD_NUM;

pthread_mutex_unlock(&(pool->lock));

for (i=0; i

{

//通知正在處于空閑的線程,自殺

pthread_cond_signal(&(pool->queue_not_empty));

printf("admin cler --n");

}

}

}

return NULL;

/ 線程是否存活 /

int

is_thread_alive(pthread_t tid)

{

int kill_rc = pthread_kill(tid, 0); //發(fā)送0號(hào)信號(hào),測試是否存活

if (kill_rc == ESRCH) //線程不存在

{

return false;

}

return true;

}

五、釋放

/ 釋放線程池 /

int

threadpool_free(threadpool_t *pool)

{

if (pool == NULL)

return -1;

if (pool->task_queue)

free(pool->task_queue);

if (pool->threads)

{

free(pool->threads);

pthread_mutex_lock(&(pool->lock)); / 先鎖住再銷毀 /

pthread_mutex_destroy(&(pool->lock));

pthread_mutex_lock(&(pool->thread_counter));

pthread_mutex_destroy(&(pool->thread_counter));

pthread_cond_destroy(&(pool->queue_not_empty));

pthread_cond_destroy(&(pool->queue_not_full));

}

free(pool);

pool = NULL;

return 0;

}

/ 銷毀線程池 /

int

threadpool_destroy(threadpool_t *pool)

{

int i;

if (pool == NULL)

{

return -1;

}

pool->shutdown = true;

/ 銷毀管理者線程 /

pthread_join(pool->admin_tid, NULL);

//通知所有線程去自殺(在自己領(lǐng)任務(wù)的過程中)

for (i=0; ilive_thr_num; i++)

{

pthread_cond_broadcast(&(pool->queue_not_empty));

}

/ 等待線程結(jié)束 先是pthread_exit 然后等待其結(jié)束 /

for (i=0; ilive_thr_num; i++)

{

pthread_join(pool->threads[i], NULL);

}

threadpool_free(pool);

return 0;

}

六、接口

/* 線程池初始化,其管理者線程及工作線程都會(huì)啟動(dòng) */

threadpool_t *thp = threadpool_create(10, 100, 100);

printf("threadpool init ... ... n");

/* 接收到任務(wù)后添加 */

threadpool_add_task(thp, do_work, (void *)p);

// ... ...

/* 銷毀 */

threadpool_destroy(thp);

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點(diǎn)僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請(qǐng)聯(lián)系本站處理。 舉報(bào)投訴
  • 接口
    +關(guān)注

    關(guān)注

    33

    文章

    8360

    瀏覽量

    150524
  • 服務(wù)器
    +關(guān)注

    關(guān)注

    12

    文章

    8849

    瀏覽量

    84950
  • C語言
    +關(guān)注

    關(guān)注

    180

    文章

    7581

    瀏覽量

    135579
  • 廣域網(wǎng)
    +關(guān)注

    關(guān)注

    1

    文章

    239

    瀏覽量

    21756
  • 線程池
    +關(guān)注

    關(guān)注

    0

    文章

    55

    瀏覽量

    6820
收藏 人收藏

    評(píng)論

    相關(guān)推薦

    C語言線程實(shí)現(xiàn)方案

    這是一個(gè)簡單小巧的C語言線程實(shí)現(xiàn),在 Github 上有 1.1K 的 star,很適合用來學(xué)習(xí) Linux 的多
    的頭像 發(fā)表于 01-29 16:43 ?1424次閱讀

    求助:如何用C語言實(shí)現(xiàn)直接尋址

    何用C語言實(shí)現(xiàn)直接尋址,就像匯編里面的mov 0x80,0x60
    發(fā)表于 05-13 16:39

    何用C語言實(shí)現(xiàn)OOP編程?

    老大看到OOP編程很好,就讓我學(xué),怎么用C語言實(shí)現(xiàn)OOP編程的,請(qǐng)大俠指點(diǎn)
    發(fā)表于 10-30 03:45

    何用C語言實(shí)現(xiàn)一款猜數(shù)字游戲

    何用C語言實(shí)現(xiàn)一款猜數(shù)字游戲
    發(fā)表于 01-06 07:10

    何用VHDL語言實(shí)現(xiàn)幀同步的設(shè)計(jì)?

    幀同步是什么工作原理?如何用VHDL語言實(shí)現(xiàn)幀同步的設(shè)計(jì)?
    發(fā)表于 04-08 06:33

    何用C語言實(shí)現(xiàn)面向?qū)ο缶幊?/a>

    、組合、多態(tài)等面向?qū)ο蟮墓δ?,?b class='flag-5'>C語言有struct和函數(shù)指針。我們可以用struct中的數(shù)據(jù)和函數(shù)指針,以此來模擬對(duì)象和類的行為。所以在正式開始設(shè)計(jì)模式前,先看看如何用C
    發(fā)表于 07-12 07:24

    何用C語言實(shí)現(xiàn)顯示16只燈的狀態(tài)并開關(guān)燈?

    何用C語言實(shí)現(xiàn)顯示16只燈的狀態(tài)并開關(guān)燈?
    發(fā)表于 10-19 09:39

    何用C語言實(shí)現(xiàn)字符數(shù)組轉(zhuǎn)換為16進(jìn)制數(shù)組?

    何用C語言實(shí)現(xiàn)字符數(shù)組轉(zhuǎn)換為16進(jìn)制數(shù)組?
    發(fā)表于 11-03 07:47

    線程是如何實(shí)現(xiàn)

    線程的概念是什么?線程是如何實(shí)現(xiàn)的?
    發(fā)表于 02-28 06:20

    DSP算法的c語言實(shí)現(xiàn)

    DSP算法的c語言實(shí)現(xiàn),又需要的朋友下來看看。
    發(fā)表于 05-09 10:59 ?0次下載

    累加校驗(yàn)和C語言實(shí)現(xiàn)

    累加校驗(yàn)和C語言實(shí)現(xiàn)
    發(fā)表于 11-29 18:06 ?10次下載
    累加校驗(yàn)和<b class='flag-5'>C</b><b class='flag-5'>語言實(shí)現(xiàn)</b>

    怎么用C語言實(shí)現(xiàn)多態(tài)

    這里我想主要介紹下在C語言中是如何實(shí)現(xiàn)的面向?qū)ο蟆V懒?b class='flag-5'>C語言實(shí)現(xiàn)面向?qū)ο蟮姆绞?,我們?cè)俾?lián)想下,C
    的頭像 發(fā)表于 10-12 09:12 ?1951次閱讀

    何用C++實(shí)現(xiàn)一個(gè)線程呢?

    C++線程是一種多線程管理模型,把線程分成任務(wù)執(zhí)行和線程調(diào)度兩部分。
    發(fā)表于 06-08 14:53 ?1649次閱讀
    如<b class='flag-5'>何用</b><b class='flag-5'>C</b>++<b class='flag-5'>實(shí)現(xiàn)</b>一個(gè)<b class='flag-5'>線程</b><b class='flag-5'>池</b>呢?

    線程基本概念與原理

    一、線程基本概念與原理 1.1 線程概念及優(yōu)勢(shì) C++線程
    的頭像 發(fā)表于 11-10 10:24 ?444次閱讀

    什么是動(dòng)態(tài)線程?動(dòng)態(tài)線程的簡單實(shí)現(xiàn)思路

    因此,動(dòng)態(tài)可監(jiān)控線程一種針對(duì)以上痛點(diǎn)開發(fā)的線程管理工具。主要可實(shí)現(xiàn)功能有:提供對(duì) Spring 應(yīng)用內(nèi)
    的頭像 發(fā)表于 02-28 10:42 ?531次閱讀