android的執行緒封裝

2021-05-24 22:56:43 字數 1505 閱讀 1318

這裡不討論具體實現,具體實現是和系統相關聯的~~首先anroid提供了幾個與直接建立執行緒的函式:

inline bool createthread(thread_func_t f, void *a)  

inline bool createthreadetc(thread_func_t entryfunction,

void *userdata,

const char* threadname = "android:unnamed_thread",

int32_t threadpriority = priority_default,

size_t threadstacksize = 0,

thread_id_t *threadid = 0)

inline thread_id_t getthreadid()

下面看看android的mutex,基本和posix的mutex很像,唯一增加了乙個mutex::autolock,這個自動鎖用得是比較多的,在 作用域裡加鎖,脫離作用域就會自動解鎖。

class autolock

inline autolock(mutex* mutex) : mpmutex(mutex)

inline ~autolock()

private:

mutex*  mpmutex;

};再看看andorid的condition,用法基本和posix差不多,因為本身是條件變數所以只有乙個mutex引數~~

最後看看android的thread類,在實際使用的過程中都是繼承這個thread類來建立自己的thread類,並定義執行緒的執行內容,下面主要圍 繞建立自己的執行緒類需要實現的幾個函式說說:

class thread : virtual public refbase

首先它繼承自refbase類,一般在使用的時候要實現onfirstref()這個父類函式,一般經典的用法是在裡面執行thread的run函式,這樣在建立thread的例項的時候就開始執行這個執行緒了。當然也可以不在這裡執行run()函式,在其他地方執行run()函式啟動這個執行緒。   

virtual status_t    run(    const char* name = 0,

int32_t priority = priority_default,

size_t stack = 0);

建立乙個thread例項的時候,執行緒並沒有執行,只有在執行run()函式的時候,執行緒才開始真正的開始執行。

virtual status_t    readytorun();

這個函式定義thread執行前的初始化工作

virtual bool        threadloop() = 0;

這個函式是每個執行緒類都要實現的,在這裡定義thread的執行內容,這個函式如果返回true,則函式會不停地執行threadloop中的內容,如果 這個函式返回false,則threadloop中的內容僅僅執行一次執行緒就會退出。

android的執行緒封裝

封裝的 檔案 frameworks base include utils threads.h 這裡不討論具體實現,具體實現是和 系統 inline bool createthread thread func t f,void a inline bool createthreadetc thread ...

android的執行緒封裝

這裡不討論具體實現,具體實現是和系統相關聯的 首先anroid提供了幾個與直接建立執行緒的函式 inline bool createthread thread func t f,void a inline bool createthreadetc thread func t entryfunctio...

簡單說說android的執行緒封裝

對執行緒的c 封裝 其實api已經寫得很清楚了 封裝的檔案 frameworks base include utils threads.h 這裡不討論具體實現,具體實現是和系統相關聯的 首先anroid提供了幾個與直接建立執行緒的函式 inline bool createthread thread ...