Linux线程的终止
生活随笔
收集整理的這篇文章主要介紹了
Linux线程的终止
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Linux線程的終止
1.線程終止的三種情況。
1.線程終止,并返回數(shù)據(jù)。
void pthread_exit(void *retval);2.取消線程。
int pthread_cancel(pthread_t thread);3.線程清理處理程序。
void pthread_cleanup_push(void (*routine)(void *),void *arg); void pthread_cleanup_pop(int execute);例1.線程清理處理程序執(zhí)行情況
例2.取消線程
執(zhí)行pthread_cancel()終止線程,線程清理處理程序會被執(zhí)行。pthread_join()將不會接收到線程啟動例程中返回的數(shù)據(jù)。
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h>static void clean_fun(void *arg) {printf("cleanup\n"); }static void *th_fun(void *arg) {int n = 0;pthread_cleanup_push(clean_fun, NULL);while (1){printf("n = %d\n", n++);sleep(1);}pthread_cleanup_pop(0);return (void *)3; }int main(int argc, char const *argv[]) {pthread_t tid;void *ret;int err;err = pthread_create(&tid, NULL, th_fun, NULL);if (err){fprintf(stderr, "thread create: %s\n", strerror(err));exit(err);}sleep(5);pthread_cancel(tid);err = pthread_join(tid, &ret);if (err){fprintf(stderr, "thread join: %s\n", strerror(err));exit(err);}printf("ret = %lu\n", (unsigned long)ret);return 0; } 執(zhí)行結(jié)果: n = 0 n = 1 n = 2 n = 3 n = 4 cleanup ret = 18446744073709551615//64位機的最大數(shù),強轉(zhuǎn)成int,是-1總結(jié)
以上是生活随笔為你收集整理的Linux线程的终止的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言-位段详解
- 下一篇: 【Linux】POSIX信号量