c 簡易執行緒池

2021-10-11 22:25:58 字數 2586 閱讀 3153

以前做均衡負載的時候就想寫過執行緒池,那時候沒有很理解就沒寫,最近嘗試自己搭個高併發的小型伺服器,又學習了下執行緒池,但感覺網上的大多涉及的技術點比較多,對於初學者不容易理解,這裡我也分享下我自己寫的簡易執行緒池,除錯環境在ubuntu18.04。

該執行緒池通過設定任務函式(搬運工)不斷地訪問等待佇列,讓所有子執行緒均執行該任務函式,只要有任務就取出執行。新增的任務以函式+引數的形式封裝推入任務佇列。當要銷毀執行緒池時,將佇列容量置零並等待所有任務完成即銷毀執行緒陣列。

該執行緒池的特點是簡單易用,執行緒無需頻繁建立銷毀的開銷,但為便於理解沒有做安全性封裝。

以下直接芳**,注釋比較詳細,應該很容易理解。

#ifndef thread_h_

#define thread_h_

#include

#include

#include

using

namespace std;

typedef

void

(*pfunc)

(void*)

;//定義函式指標pfunc

struct pf //封裝函式指標與引數

;class

thread_pool

;#endif

#include

#include

"thread.h"

using

namespace std;

void

* thread_pool::

worker

(void

* arg)

//工作執行緒

p->busy_thread++

;//忙執行緒+1

struct pf tmp=p-

>wait_queue.

front()

;

p->wait_queue.

pop();

//取出任務

pthread_mutex_unlock

(&p-

>m_mutex1)

; tmp.

fun(tmp.arg)

;//執行任務,這裡一般不進行阻塞

pthread_mutex_lock

(&p-

>m_mutex2)

;//防止競爭

p->busy_thread--

;//忙執行緒-1

p->busy_task--

;//忙任務-1

cout<<

"完成任務"

<

pthread_mutex_unlock

(&p-

>m_mutex2);}

};thread_pool::

thread_pool

(int m_th,

int w_th)

:max_thread

(m_th)

,busy_thread(0

),max_wait

(w_th)

,busy_task(0

)};thread_pool::

~thread_pool()

bool thread_pool::

add_task

(pfunc pfc,

void

* arg)

; wait_queue.

push

(newpf)

;//將任務函式與引數加入

busy_task++

;pthread_mutex_unlock

(&m_mutex1)

;sem_post

(&m_sem)

;//任務增加,訊號量+1

return

true;}

cout<<

"佇列已滿"

<

pthread_mutex_unlock

(&m_mutex1)

;return

false;}

;void thread_pool::

close_pool()

#include

#include

"thread.h"

using

namespace std;

void

work1

(void

* arg)

printf

("%d"

,sum);}

intmain()

tp.close_pool()

;return0;

}

//makefile

flag = $

main: main.cpp thread.cpp

g++ main.cpp thread.cpp -o main $

-lpthread

如果有問題與改進的地方也希望小夥伴們指正!

C 簡易執行緒池

原理 thread a thread theadproc,param 執行緒構造以後,執行緒執行的函式就不能改變了,一旦函式執行結束,執行緒也就終止。所以要實現執行緒不停的切換任務,就只能對param動手了。讓param變成乙個裝有函式指標以及該函式執行所需引數的資料結構。讓執行緒池和執行緒通過pa...

簡易執行緒池實現

是其實也就是任務分發器,池子裡預先跑著n個執行緒,可以往池子裡提交任務。相對執行緒不斷建立和銷毀,特別對於大量的短時任務,執行緒池顯然是很節省資源的。直接上 include include include include include include typedef void job void d...

python手寫簡易執行緒池

bin env python coding utf 8 import queue import threading from contextlib import contextmanager import time 停止事件 stopevent object class threadpool obj...