- 论坛徽章:
- 4
|
- /* example5.c */
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <pthread.h> /* 包含相关函数头文件 */
- void* mythread(void *) /* 定义新线程运行的函数 */
- {
- int i,ret;
- ret = pthread_setcancelstate( /* 设置线程的取消状态 */
- PTHREAD_CANCEL_ENABLE, NULL);
- if(ret != 0)
- {
- printf("Thread pthread_setcancelsate failed."); /* 如果取消状态未设置成功,打印错误信息 */
- exit(1);
- }
- ret = pthread_setcanceltype( /* 设置线程的取消类型 */
- PTHREAD_CANCEL_DEFERRED, NULL);
- if(ret != 0)
- {
- printf("Thread pthread_setcanceltype failed."); /* 如果取消类型未设置成功,打印错误信息 */
- exit(1);
- }
- for(i=0; i<5; i++) /* 连续输出字符串,同时显示运行位置 */
- {
- printf("Thread is running (%d) ...\n",i);
- sleep(1);
- }
- pthread_exit((void *)"Thank you for the CPU time.\n"); /* 终止当前线程 */
- }
- int main()
- {
- pthread_t id; /* 定义线程的标识符 */
- int ret;
- void *thread_result; /* 定义指针,用来存储线程的返回值 */
- ret = pthread_create(&id, NULL, mythread, NULL); /* 创建新的线程 */
- if(ret != 0)
- {
- printf("Create pthread error.\n"); /* 如果线程创建失败,打印错误信息 */
- exit(1);
- }
- sleep(3);
- printf("Canceling thread ...\n");
- ret = pthread_cancel(id); /* 取消新建线程 */
- if(ret != 0)
- {
- printf("Thread cancelation failed.\n"); /* 如果线程取消失败,打印错误信息 */
- exit(1);
- }
- sleep(2);
- /* 主线程阻塞,等待新建线程返回,并将返回值存储在前面定义的thread_result之中 */
- pthread_join(id,&thread_result);
-
- if (thread_result == PTHREAD_CANCELED )
- {
- printf("cancel\n"); /* 输出线程返回的字符串 */
- }
- else
- {
- printf("Thread joined, it returned: %s", (char *)thread_result);
- }
-
- return 0;
- }
复制代码linux_c_py_php 发表于 2012-11-10 12:55
If the target thread was canceled, then PTHREAD_CANCELED is placed in *retval.
同学, 不是每个返回 ...
还有, 代码规范点, 线程函数是那么定义的吗? |
|