pthread Cancel and Signal
Thread 也是 process
Linux 排程時每個 thread 都有自己的 tid(gettid()),kill -s SIG <tid> 會讓該 thread 執行 signal handler。
pthread_kill
- 在 process 內對指定 thread 送 signal
- 被 signal 打斷的
sleep等 blocking call 會提早返回
pthread_cancel
- 只在 cancellation point(大多是 IO、
sleep等 blocking call)中斷 thread - glibc 實作:對目標 thread 送 signal → handler 呼叫
__do_cancel→__pthread_unwind→_Unwind_ForcedUnwind - 因為是 forced unwind,glibc 下 C++ destructor 會被呼叫;macOS(Apple clang)實測不會
- 行為不在標準內,跨平台不要依賴,一般也不建議用
pthread_cancel
參考
- 原文:pthread_cancel 與解構子行為實驗、pthread_kill 實驗
- pthread_cancel(3)、pthread_kill(3)
- pthread_cancel considered harmful