读书人

pthread_cancel为啥不好用呢?

发布时间: 2012-09-06 10:37:01 作者: rapoo

pthread_cancel为什么不好用呢??
新手学习linux,为什么不好使呢下面的代码,求解释。。。。。
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>

void CleanUp(void *arg)
{
printf("clean up:%s\n",(char *)arg);
}

void *Func(void *arg)
{
printf("Enter thread\n");
int nRet,nOld;
nRet = pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &nOld);
nRet = pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &nOld);
pthread_cleanup_push(CleanUp, "thread");

printf("Ready to sleep\n");
sleep(2);
printf("before testcancel\n"); //直接不打印这句,为啥?

pthread_testcancel();
printf("after testcancel\n");
pthread_cleanup_pop(0);
//return ((void*)NULL);
pthread_exit((void*)NULL);
}

int main()
{
pthread_t tid;
int n;
printf("Enter Main\n");
n = pthread_create(&tid, NULL, Func, NULL);
if(n != 0)
printf("Create thread error!");

sleep(1);
pthread_cancel(tid);
pthread_join(tid, NULL);
printf("Main done\n");

return 0;
}


第二个问题,上述两个sleep一定需要加吗?不加有什么后果呢??谢谢。。

[解决办法]
线程没有同步啊,不同的线程代码执行的先后就很难说的了。pthread_cancel(tid)这里就明显是在sleep(2)的过程中执行的。
[解决办法]
因为在设计层面,任何在外部让线程结束的主意都是一个错误。

读书人网 >C语言

热点推荐