造輪子之執行緒控制類的封裝

2021-09-26 16:07:21 字數 2844 閱讀 1288

執行緒常用方法

int pthread_join(pthread_t thread, void **retval);

int pthread_detach(pthread_t thread);

pthread_t pthread_self(void);

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,

void *(*start_routine) (void *), void *arg);

定義
/**

* @brief 執行緒控制異常類

*/struct yr_threadthreadcontrol_exception : public yr_exception

; yr_threadthreadcontrol_exception(const string &buffer, int err) : yr_exception(buffer, err){};

~yr_threadthreadcontrol_exception() throw() {};

};/**

* @brief 執行緒控制類

*/class yr_threadcontrol

;

實現

構造和析構

yr_threadcontrol::yr_threadcontrol(pthread_t thread) : _thread(thread)

yr_threadcontrol::yr_threadcontrol() : _thread(pthread_self())

控制方法
void yr_threadcontrol::join()

void* ignore = 0;

int rc = pthread_join(_thread, &ignore);

if(rc != 0)

}void yr_threadcontrol::detach()

int rc = pthread_detach(_thread);

if(rc != 0)

}pthread_t yr_threadcontrol::id() const

void yr_threadcontrol::sleep(long millsecond)

void yr_threadcontrol::yield()

執行緒基類的定義
class yr_runable

; virtual void run() = 0;

};/**

* @brief 執行緒基類.

* 執行緒基類,所有自定義執行緒繼承於該類,同時實現run介面即可,

* * 可以通過yr_threadcontorl管理執行緒。

*/class yr_thread : public yr_runable

; /**

* @brief 執行緒執行

*/yr_threadcontrol start();

/*** @brief 獲取執行緒控制類.

** @return threadcontrol

*/yr_threadcontrol getthreadcontrol() const;

/*** @brief 執行緒是否存活.

** @return bool 存活返回true,否則返回false

*/bool isalive() const;

/*** @brief 獲取執行緒id.

** @return pthread_t 執行緒id

*/pthread_t id()

protected:

/*** @brief 靜態函式, 執行緒入口.

* * @param pthread 執行緒物件

*/static void threadentry(yr_thread *pthread);

/*** @brief 執行

*/virtual void run() = 0;

protected:

/*** 是否在執行

*/bool _running;

/*** 執行緒id

*/pthread_t _tid;

/*** 普通執行緒鎖

*/yr_threadlock _lock;

};

實現

構造

yr_thread::yr_thread() : _running(false),_tid(-1)

執行緒入口
void yr_thread::threadentry(yr_thread *pthread)

trycatch(...)

pthread->_running = false;

}

執行緒啟動
yr_threadcontrol yr_thread::start()

int ret = pthread_create(&_tid,

0,(void *(*)(void *))&threadentry,

(void *)this);

if(ret != 0)

_lock.wait();

return yr_threadcontrol(_tid);

}

其他函式實現
yr_threadcontrol yr_thread::getthreadcontrol() const

bool yr_thread::isalive() const

造輪子之執行緒鎖監控類的封裝

互斥鎖乙個明顯的缺點是它只有兩種狀態 鎖定和非鎖定。而條件變數通過允許執行緒阻塞和等待另乙個執行緒傳送訊號的方法彌補了互斥鎖的不足,它常和互斥鎖一起配合使用。使用時,條件變數被用來阻塞乙個執行緒,當條件不滿足時,執行緒往往解開相應的互斥鎖並等待條件發生變化。一旦其他的某個執行緒改變了條件變數,他將通...

造輪子之執行緒安全佇列的封裝

c 中雖然有std queue std deque這些佇列容器,但是不是執行緒安全的,因此我們需要封裝乙個執行緒安全的執行緒佇列。定義template class yr thread queue protected yr threadlock public void push front const...

造輪子之常用函式的封裝

常用函式的封裝 時間操作常用函式 幫助類定義 字串操作封裝class yr common 實現string yr common trim const string sstr,const string s,bool bchar string yr common trimleft const strin...