linux C實現執行緒池

2021-09-26 08:06:34 字數 1975 閱讀 6862

執行緒池包括任務佇列,執行緒陣列,管理模組幾個部分,依次實現這幾個模組

typedef struct tk_tasktk_task_t;
任務佇列,用單鏈表的方式實現

執行緒池的管理模組用以下

typedef struct threadpooltk_threadpool_t;
要實現以下幾個方法

tk_threadpool_t* threadpool_init(int thread_num);

int threadpool_add(tk_threadpool_t* pool, void (*func)(void *), void* arg);

int threadpool_destroy(tk_threadpool_t* pool, int gracegul);

初始化方法要來初始化任務節點,建立執行緒陣列,設定一系列初始化等操作

在建立執行緒時,給執行緒繫結上乙個函式,這個函式定義了執行緒需要執行的操作

// 初始化執行緒池

tk_threadpool_t *threadpool_init(int thread_num)

pool->thread_count++;

pool->started++;

}return pool;

err:

if(pool)

threadpool_free(pool);

return null;

}

執行緒繫結的函式是

void *threadpool_worker(void *arg)

// 存在task則取走並開鎖

pool->head->next = task->next;

pool->queue_size--;

pthread_mutex_unlock(&(pool->lock));

// 設定task中func引數

(*(task->func))(task->arg);

free(task);

}pool->started--;

pthread_mutex_unlock(&(pool->lock));

pthread_exit(null);

return null;

}

執行緒首先對整個執行緒池進行加鎖,如果發現執行緒池已經加鎖了,那麼阻塞等待。如果發現任務隊列為空,那麼條件等待。執行緒池從任務佇列拿乙個任務,執行任務佇列中的函式。

下面是像條件變數中新增任務。

int threadpool_add(tk_threadpool_t* pool, void (*func)(void *), void *arg)

// 新建task並註冊資訊

tk_task_t *task = (tk_task_t *)malloc(sizeof(tk_task_t));

if(task == null)

goto out;

task->func = func;

task->arg = arg;

// 新task節點在head處插入

task->next = pool->head->next;

pool->head->next = task;

pool->queue_size++;

rc = pthread_cond_signal(&(pool->cond));

out:

if(pthread_mutex_unlock(&pool->lock) != 0)

return -1;

return err;

}

linux C 執行緒池 獨佔共享鎖實現

如果乙個應用需要頻繁的建立和銷毀執行緒,而任務執行的時間又非常短,這樣執行緒建立和銷毀的帶來的開銷就不容忽視,這時也是執行緒池該出場的機會了。如果執行緒建立和銷毀時間相比任務執行時間可以忽略不計,則沒有必要使用執行緒池了,本文使用共享獨佔模式實現執行緒池中任務同步與互斥。使用場景主要用於寫入任務較少...

linux c 執行緒池開發demo

condition.h ifndef condition h define condition h include typedef struct conditioncondition t int condition init condition t cond 初始化 int condition lo...

高效執行緒池之無鎖化實現 Linux C

筆者之前照著通用寫法練手寫過乙個小的執行緒池版本,最近幾天複習了一下,發現大多數執行緒池實現都離不開鎖的使用,如互斥量pthread mutex 結合條件變數pthread cond 眾所周知,鎖的使用對於程式效能影響較大,雖然現有的pthread mutex 在鎖的申請與釋放方面做了較大的優化,但...