執行緒取消:
取消操作允許執行緒請求終止其所在程序總的任何其他執行緒。不需要執行緒執行進一步操作時,可以選擇取消操作。
取消點:
如果執行緒模式設定的是非同步模式的話,那只有到取消點才會取消執行緒。下面會講到兩種取消方式。
那取消點有哪些呢?
1:通過pthread_testcancel 呼叫已程式設計方式建立執行緒取消點
2:執行緒等待pthread_cond_wait或pthread_cond_timewait中的特定條件
3:被sigwait(2)阻塞的函式
4:一些標準的庫呼叫。通常這些呼叫包括執行緒可基於阻塞的函式
default情況下,會啟用取消功能。
posix標準中,pthread_join(),pthread_testcancel().pthread_cond_wait(),pthread_cond_timewait(),sem_wait(),sigwait()等函式以及read,write等會引起阻塞的系統呼叫。
取消執行緒函式
int pthread_cancel(pthread_t thread);
成功之後返回0,失敗返回錯誤號,錯誤號說明如下:
esrch:沒有找到執行緒id相對應的執行緒。
int phread_setcancelstate(int state,int *oldstate);設定本執行緒對訊號的反應:
狀態:pthread_cancel_enable 預設,收到cancel訊號馬上設定退出狀態
pthread_cancel_disable 很明顯不處理cancel
返回值:
成功之後返回0.失敗返回錯誤號,錯誤號說明如下:
einval:狀態不是pthread_cancel_enable或者pthread_cancel_disable
那取消方式呢?取消方式有兩種,當然只有在pthread_cancel_enable狀態下有效
int pthread_setcanceltype(int type, int *oldtype);
pthread_cancel_asynchronous 立即執行取消訊號
pthread_cancel_deferred 執行到下乙個取消點
有什麼區別呢?
在延遲模式(pthread_cancel_deferred)下,只能在取消點取消執行緒,在非同步模式下,可以在任意一點取消執行緒,這建立還是用延遲模式
注意:當取消執行緒後,執行緒裡面的鎖可能還沒有unlock,那麼就會出現死鎖的情況,如何避免呢?
這裡介紹下清理處理程式,它可以將狀態恢復到與起點一致的狀態,其中包括清理已分配的資源和恢復不變數。
使用pthread_cleanup_push和pthread_cleanup_pop,
push函式是將處理程式推送到清理棧,執行順序自然是fifo
void pthread_cleanup_push(void(*routine)(void *) , void (args);
有了這個清理函式,我們只需要把執行緒要清理的函式push上去,把unlock放在裡面,就不會死鎖了,當然之前還要lock一下mutex。
voidcleanup(
void*arg)
這裡舉個取消點的例子:
#include #include #include void* thr(void* arg)
printf("thread is not running\n");
sleep(2);
}int main()
執行緒操作 取消執行緒
include include include include 包含執行緒庫 void thread function void arg 定義執行緒函式原型 int main sleep 3 睡眠3秒 printf 取消執行緒.n res pthread cancel a thread 傳送取消執行...
執行緒取消 pthread cancel
基本概念 pthread cancel呼叫並不等待執行緒終止,它只提出請求。執行緒在取消請求 pthread cancel 發出後會繼續執行,直到到達某個取消點 cancellationpoint 取消點是執行緒檢查是否被取消並按照請求進行動作的乙個位置.與執行緒取消相關的pthread函式 int...
posix執行緒 執行緒的取消
初看這個主題時,覺得實在簡單。在我印象中,執行緒取消的實現通常是宣告乙個全域性變數來代表取消標誌,乙個執行緒在最開始的大while中判斷該標誌是否被設定,如果被設定就跳出迴圈。但是這有乙個問題是,如果程式中有n個執行緒都有可能被取消,那麼我們是否要宣告n個全域性變數來單獨控制它們的取消?posix提...