cancel(了解)
- 功能:发送取消请求
- 原型:
int pthread_cancel(pthread_t thread);
- 参数:
1)tid - 返回值:
成功:返回0
失败:返回非0 - 取决于线程的属性:
a.是否响应:取消state,pthread_setcancelstate
b.如何响应:取消type,pthread_setcanceltype
c.取消点:可能会陷入后时间阻塞,例:sleep,pthread_testcancel() - DO
#include <func.h>
void* start_routine(void* args) {
while (1) {
pthread_testcancel();
printf("Hello World\n");
sleep(2);
}
}
int main(int argc, char* argv[]) {
pthread_t tid;
int err = pthread_create(&tid, NULL, start_routine, NULL);
if (err) {
error(1, err, "pthread_create");
}
sleep(1);
err = pthread_cancel(tid);
if (err) {
error(1, err, "pthread_cancel %lu", tid);
}
err = pthread_join(tid, NULL);
if (err) {
error(1, err, "pthrad_join %lu", tid);
}
return 0;
}