C 11的多執行緒併發程式設計(六)

2021-10-02 23:10:25 字數 2347 閱讀 7064

這篇主要記錄執行緒池的寫法,執行緒池就是有一堆已經建立好了的執行緒,初始都處於空閒等待狀態,當有任務需要處理是,就從執行緒池中取乙個空閒等待的執行緒來處理該仍無,等任務處理完畢後,就再次把執行緒放回池中,其實就是設定執行緒的狀態,當執行緒池裡的都處於忙碌狀態,那麼就根據需要建立乙個新的執行緒,或者等待。

threadpool.h

標頭檔案主要用來寫任務類,定義任務類成員,以及成員函式,以及執行緒池管理類,定義執行緒數目,任務列表,執行緒入口函式,以及執行緒切換狀態函式。

#ifndef _thread_pool_h

#define _thread_pool_h

#include

#include

#include

#include

using

namespace std;

//this class is for task excuting

class

ctask

virtual

intrun()

=0;void

setdata

(void

* data)

;virtual

~ctask()

};class

cthreadpool

;#endif

2.threadpool.cpp

主要用來設定成員初始化,定義執行緒成員函式,新增任務函式,建立執行緒函式,這裡用的都是linux提供的poxis的執行緒api,學習學習。

#include

"threadpool.h"

#include

#include

void ctask::

setdata

(void

*data)

vector

> cthreadpool::vectasklist;

bool cthreadpool::shutdown =

false

;pthread_mutex_t cthreadpool::pthreadmutex = pthread_mutex_initializer;

pthread_cond_t cthreadpool::pthreadcond = pthread_cond_initializer;

cthreadpool::

cthreadpool

(int threadnums)

void

*cthreadpool::

threadfunc

(void

*threaddata)

printf

("[tid: %lu]\trun: "

, tid)

; vector

>

::iterator iter = vectasklist.

begin()

; ctask *task =

*iter;

if(iter != vectasklist.

end())

pthread_mutex_unlock

(&pthreadmutex);

task-

>

run();

printf

("[tid: %lu]\tidle\n"

, tid);}

return

(void*)

0;}int cthreadpool::

addtask

(ctask *task)

int cthreadpool::

create()

int cthreadpool::

stopall()

int cthreadpool::

gettasksize()

main.cpp

#include

"threadpool.h"

#include

#include

#include

#include

class

cmytask

:public ctask

~cmytask()

};intmain()

}sleep(2

);cout <<

"2 seconds later..."

<< endl;

}return0;

}

執行結果如圖所示:

程式穩定執行,留著以後要用的時候參考。

C 11併發程式設計 多執行緒std thread

c 11引入了thread類,大大降低了多執行緒使用的複雜度,原先使用多執行緒只能用系統的api,無法解決跨平台問題,一套 平台移植,對應多執行緒 也必須要修改。現在在c 11中只需使用語言層面的thread可以解決這個問題。所需標頭檔案 thread noexcept 乙個空的std thread...

C 11 多執行緒 併發程式設計總結

建立std thread,一般會繫結乙個底層的執行緒。若該thread還繫結好函式物件,則即刻將該函式執行於thread的底層執行緒。執行緒相關的很多預設是move語義,因為在常識中線程複製是很奇怪的行為。joinable 是否可以阻塞至該thread繫結的底層執行緒執行完畢 倘若該thread沒有...

C 11併發程式設計 多執行緒std thread

一 概述 c 11引入了thread類,大大降低了多執行緒使用的複雜度,原jtpbyn先使用多執行緒只能用系統的api,無法解決跨平台問題,一套 平台移植,對應多執行緒 也必須要修改。現在在c 11中只需使用語言層面的thread可以解決這個問題。所需標頭檔案 二 建構函式 1.預設建構函式 2.初...