c – 何时使用pthread_exit()以及何时在Linux中使用pthread_join()?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c – 何时使用pthread_exit()以及何时在Linux中使用pthread_join()?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1626字,纯文字阅读大概需要3分钟。
内容图文
![c – 何时使用pthread_exit()以及何时在Linux中使用pthread_join()?](/upload/InfoBanner/zyjiaocheng/951/4be2acfddd3045c8ba12aaf3d0c1280d.jpg)
我是pthreads的新手,我正在努力理解它.我看到了一些如下例子.
我可以看到main()被API pthread_exit()阻止了,我看到了API pthread_join()阻止了main函数的例子.我无法理解何时使用什么?
我指的是以下站点 – https://computing.llnl.gov/tutorials/pthreads/.我无法获得何时使用pthread_join()以及何时使用pthread_exit()的概念.
有人可以解释一下吗?此外,pthreads的良好教程链接将不胜感激.
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
if (rc){
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
/* Last thing that main() should do */
pthread_exit(NULL);
实现了一件事,即
pthread_cancel(thread);
pthread_join(thread, NULL);
有时,您希望在执行时取消该线程.
你可以使用pthread_cancel(thread);来完成这个.
但是,请记住,您需要启用pthread取消支持.
此外,取消时清理代码.
thread_cleanup_push(my_thread_cleanup_handler, resources);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
static void my_thread_cleanup_handler(void *arg)
{
// free
// close, fclose
}
解决方法:
正如openpub文档中所解释的那样,
pthread_exit()将退出调用它的线程.
在你的情况下,主要调用它,主线程将终止,而你的衍生线程将继续执行.这主要用于以下情况
主线程只需要生成线程并让线程完成它们的工作
pthread_join
除非目标线程终止,否则将暂停执行已调用它的线程
这在您希望等待thread / s进一步终止之前的情况下非常有用
在主线程中处理.
内容总结
以上是互联网集市为您收集整理的c – 何时使用pthread_exit()以及何时在Linux中使用pthread_join()?全部内容,希望文章能够帮你解决c – 何时使用pthread_exit()以及何时在Linux中使用pthread_join()?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。