- 论坛徽章:
- 0
|
Figure 11.5 shows how to use thread cleanup handlers. Although the example is somewhat contrived, it illustrates the mechanics involved. Note that although we never intend to pass a nonzero argument to the thread start-up routines, we still need to match calls to pthread_cleanup_pop with the calls to pthread_cleanup_push; otherwise, the program might not compile.
不太明白红色标识部分的意思
结合实例,不知道为什么在thr_fn1()和thr_fn2()中arg为非空的时候,就不需要调用pthread_cleanup_pop()
实例代码如下
- #include <stdlib.h>
- #include <stdio.h>
- void cleanup(void *arg)
- {
- printf("cleanup: %s\n", (char *)arg);
- }
- void *thr_fn1(void *arg)
- {
- printf("thrad 1 start\n");
- pthread_cleanup_push(cleanup, "thread 1 first handler");
- pthread_cleanup_push(cleanup, "thread 1 second handler");
- printf("thread 1 push complete\n");
-
- if (arg)
- return ((void *)1);
- pthread_cleanup_pop(0);
- pthread_cleanup_pop(0);
- return ((void *)1);
- }
- void *thr_fn2(void *arg)
- {
- printf("thread 2 start\n");
- pthread_cleanup_push(cleanup, "thread 2 first handler");
- pthread_cleanup_push(cleanup, "thread 2 second handler");
- printf("thread 2 push complete\n");
-
- if (arg)
- pthread_exit((void *)2); //为什么arg为非空的时候,就不需要调用pthread_cleanup_pop()
- pthread_cleanup_pop(0);
- pthread_cleanup_pop(0);
- pthread_exit((void *)2);
- }
- int main(void)
- {
- int err;
- pthread_t tid1, tid2;
- void *tret;
- // err = pthread_create(&tid1, NULL, thr_fn1, (void *)1);
- err = pthread_create(&tid1, NULL, thr_fn1, NULL);
- if (err != 0)
- {
- printf("can't create thread 1:%s\n", strerror(errno));
- exit(0);
- }
- err = pthread_create(&tid2, NULL, thr_fn2, (void *)2);
- // err = pthread_create(&tid2, NULL, thr_fn2, NULL);
- if (err != 0)
- {
- printf("can't create thread 2:%s\n", strerror(errno));
- exit(0);
- }
- err = pthread_join(tid1, &tret);
- if (err != 0)
- {
- printf("can't join with thread 1:%s\n", strerror(errno));
- exit(0);
- }
- printf("thread 1 exit code %d\n", (int)tret);
- err = pthread_join(tid2, &tret);
- if (err != 0)
- {
- printf("can't join with thread 2:%s\n", strerror(errno));
- exit(0);
- }
- printf("thread 2 exit code %d\n", (int)tret);
- exit(0);
- }
复制代码
[ 本帖最后由 zhuhefang2006 于 2009-1-13 16:04 编辑 ] |
|