您的位置:首页 > 其它

2.pthread_join()、pthread_exit()、pthread_cancel()简述

2013-08-01 17:59 465 查看
继续回到解决程序

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *sayhello(void *arg)
{
printf("hello, world! I'm son\n");
}
int main(void)
{
int error;
pthread_t son;
error = pthread_create(&son, NULL, sayhello, NULL);
printf("hello, world! I'm father\n");
return 0;
}
的问题上!

也即让“printf("hello, world! I'm son\n");”和“printf("hello, world! I'm father\n");”都能够执行。

《pthread_create()初体验》已经给出了三个解决办法:

方法1:在“return 0;”之前加上一句“sleep(1);”

方法2:在“父进程”所对应程序中加上一句“pthread_join()”

方法3:在“父进程”所对应程序中加上一句“pthread_exit(NULL)”

pthread_exit(NULL)和pthread_join()的功能差不多,只是后者从退出的子线程获取退出状态码(具体如何获取就不知道了)!

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *sayhello(void *args)
{
printf("hello, world! I'm son\n");
}
int main(void)
{
int error;
pthread_t son;
error = pthread_create(&son, NULL, sayhello, NULL);
printf("hello, world! I'm father\n");
//pthread_join(son, NULL);
pthread_exit(NULL);
//sleep(1);
return 0;
}


pthread_join函数可以使调用这个函数的线程等待指定的线程运行完成再继续执行,它的形式为:

int pthread_join(pthread_t thread, void **value_ptr);

参数thread为要等待的线程的ID,参数value_ptr为执行返回值的指针提供一个位置,这个返回值是由目标线程传递给pthread_exit或return的。如果value_ptr为NULL,调用程序就不会对目标线程的返回状态进行检索了。如果调用成功,pthread_join返回0...

关于第二个参数,还不知道怎么用它,通常它都是NULL!

pthread_exit函数可以使调用这个函数的线程终止运行,并且允许线程传递一个指针,这个指针可以用来指向线程的返回值。它的形式为:

void pthread_exit(void *value_ptr);

回顾上面的pthread_join函数,这个函数的参数void **value_ptr,正是保存pthread_exit函数的参数void *value_ptr的地址。这里要注意,pthread_exit的参数value_ptr必须指向线程退出后仍然存在的数据。

这样看来,pthread_exit没办法终止其他线程,只能终止调用这个函数的线程。

问题,pthread_exit()为什么能够起到pthread_join函数的作用呢?

再来个测试:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *sayhello(void *args)
{
sleep(1);
printf("hello, world! I'm son\n");
}
int main(void)
{
int error;
pthread_t son;
error = pthread_create(&son, NULL, sayhello, NULL);
printf("hello, world! I'm father\n");
//pthread_join(son, NULL);
pthread_exit(NULL);
//sleep(1);
return 0;
}


编译执行结果如下:

root@book-desktop:/opt/pc_test/multithreading/2# ./main

hello, world! I'm father

hello, world! I'm son

由此猜测性得出结论,pthread_exit()的作用确实是终止调用它的线程,但在此之前,它会等待子线程全部执行完!!!

但是,父进程想退出,而又不想子线程执行完那该怎么办?有办法,还有pthread_cancel()函数,通过它来请求取消另一个线程,此函数的形式是:

int pthread_cancel(pthread_t thread);

参数thread是要取消的目标线程的线程ID。该函数并不阻塞调用线程,它发出请求后就返回了。如果成功,pthread_cancel返回0。如果不成功,pthread_cancel返回一个非零的错误码。(感觉这句话有矛盾,前面讲“不阻塞调用线程”,后面又讲“如果不成功...”,这里的不成功是什么意思?是指请求失败,还是指终止失败)。

就这样吧...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: