标签:style blog class code c ext
void pthread_exit(void *rval_ptr); // 退出线程,可通过参数向其它线程传递信息 int pthread_join(pthread_t thread, void **rvalptr); // 阻塞等待指定线程退出,可获得线程退出时的信息
#include <stdio.h>
#include <pthread.h>
void *thr_fn1(void *arg)
{
printf("thread 1 returning\n");
return ((void *)1);
}
void *thr_fn2(void *arg)
{
printf("thread 2 returning\n");
pthread_exit((void *)2);
}
int main(void)
{
pthread_t tid1, tid2;
void *ret;
pthread_create(&tid1, NULL, thr_fn1, NULL);
pthread_create(&tid2, NULL, thr_fn2, NULL);
pthread_join(tid1, &ret); // 等待线程1退出
printf("thread 1 exit code = %d\n", (int)ret);
pthread_join(tid2, &ret); // 等待线程2退出
printf("thread 2 exit code = %d\n", (int)ret);
return 0;
}
int pthread_cancel(pthread_t tid); // 请求取消同一进程中的指定线程
pthread_exit(PTHREAD_CANCELED);
void pthread_cleanup_push(void (*rtn)(void *), void *arg); // 注册清理函数 void pthread_cleanup_pop(int execute); // 根据参数决定是否调用清理函数
#include <stdio.h>
#include <pthread.h>
// 线程清理处理程序
void cleanup(void *arg)
{
printf("cleanup : %s\n", (char *)arg);
}
void *thr_fn1(void *arg)
{
pthread_cleanup_push(cleanup, "This is thread 1\n");
return ((void *)1); // 返回不会调用清理函数
pthread_cleanup_pop(0); // 配对作用
}
void *thr_fn2(void *arg)
{
pthread_cleanup_push(cleanup, "This is thread 2\n");
pthread_exit((void *)2); // exit时会调用清理函数
pthread_cleanup_pop(0); // 配对作用
}
void *thr_fn3(void *arg)
{
pthread_cleanup_push(cleanup, "This is thread 3\n");
sleep(3); // 等待控制线程发出取消请求,然后调用清理函数
pthread_cleanup_pop(0); // 配对作用
}
void *thr_fn4(void *arg)
{
pthread_cleanup_push(cleanup, "This is thread 4\n");
pthread_cleanup_pop(1); // 参数为0,则清理函数不被调用
}
int main(void)
{
pthread_t tid1, tid2, tid3, tid4;
pthread_create(&tid1, NULL, thr_fn1, NULL);
pthread_create(&tid2, NULL, thr_fn2, NULL);
pthread_create(&tid3, NULL, thr_fn3, NULL);
pthread_create(&tid4, NULL, thr_fn4, NULL);
pthread_cancel(tid3);
sleep(3);
return 0;
}
标签:style blog class code c ext
原文地址:http://blog.csdn.net/nestler/article/details/25697093