執行緒池程式設計示例

2021-08-08 15:16:10 字數 2281 閱讀 5448

示例**:

#include 

#include

#include

#include

#include

#include

typedef struct workercthread_worker; /*執行緒池結構*/ typedef struct cthread_pool; int pool_add_worker(void *(*process)(void *arg), void *arg); void *thread_routine(void *arg); static cthread_pool *pool = null; void pool_init(int max_thread_num) int pool_add_worker(void *(*process)(void *arg), void *arg) else assert(pool->queue_head != null); pool->cur_queue_size++; pthread_mutex_unlock(&(pool->queue_lock)); pthread_cond_signal(&(pool->queue_ready));/*呼叫pthread_cond_signal來喚醒乙個等待執行緒。若所有執行緒都在忙,則該語句無效*/ return 0; } int pool_destroy() free(pool->threadid); cthread_worker *head = null; while(pool->queue_head != null) /*依次順序釋放任務鍊錶中的每個任務對應的cthread_worker占用的記憶體*/ pthread_mutex_destroy(&(pool->queue_lock)); pthread_cond_destroy(&(pool->queue_ready)); /*喚醒所有等待執行緒以便銷毀執行緒池*/ free(pool); pool = null; return 0; } void *thread_routine(void *arg) if (pool->shutdown) assert(pool->cur_queue_size != 0); assert(pool->queue_head != null); pool->cur_queue_size--; cthread_worker *worker = pool->queue_head; pool->queue_head = worker->next; pthread_mutex_unlock(&(pool->queue_lock)); (*(void *)(worker->process)((void *)worker->arg)); free(worker); worker = null; } pthread_exit(null); } void *myprocess(void *arg) int main(int argc, char **argv) sleep(5); pool_destroy(); free(workingnum); return 0; }

編譯完成後執行結果如下:

ubuntu:~$ ./threadpool

start thread 0xb751bb40

threadid is 0xb751bb40, working on task 0

start thread 0xb6d1ab40

threadid is 0xb6d1ab40, working on task 1

start thread 0xb6519b40

threadid is 0xb6519b40, working on task 2

threadid is 0xb751bb40, working on task 3

threadid is 0xb6d1ab40, working on task 4

threadid is 0xb6519b40, working on task 5

threadid is 0xb751bb40, working on task 6

threadid is 0xb6d1ab40, working on task 8

threadid is 0xb6519b40, working on task 7

threadid is 0xb751bb40, working on task 9

thread 0xb6d1ab40 is waiting

thread 0xb6519b40 is waiting

thread 0xb751bb40 is waiting

thread 0xb6d1ab40 will exit

thread 0xb6519b40 will exit

thread 0xb751bb40 will exit

執行緒池服務程式設計

1 原理分析 執行緒池的核心設計思想是系統在初始化時,建立一定數量的服務執行緒,並使他們處於空閒狀態,若當前有新使用者到來,則系統先查詢當前有無空閒執行緒,若有則立即為其分配服務執行緒,如沒有,則將新使用者加入待服務佇列,並在其他使用者結束服務時,再重新為其分配服務執行緒。新使用者如果在等待服務佇列...

網路程式設計 執行緒池

在乙個池子裡,放固定數量的執行緒,這些執行緒等待任務,一旦有任務來,就有執行緒自發的去執行任務。concurrent.futures 這個模組是非同步呼叫的機制 concurrent.futures 提交任務都是用submit for submit 多個任務的提交 shutdown 是等效於pool...

linux執行緒程式設計示例

執行緒程式設計和rtos實時任務建立差不多,比程序更節省資源 執行緒標頭檔案 include 函式原型 1.建立執行緒 int pthread create pthread t thread,const pthread attr t attr,void start routine void void...