在下面的程序当中我们使用 pthread_join 函数去等待一个 detached 线程:
#include <stdio.h>#include <error.h>#include <errno.h>#include <pthread.h>#include <unistd.h>pthread_t t1, t2;void* thread_1(void* arg) { int ret = pthread_detach(pthread_self()); sleep(2); if(ret != 0) perror(""); return NULL;}int main() { pthread_create(&t1, NULL, thread_1, NULL); sleep(1); int ret = pthread_join(t1, NULL); if(ret == ESRCH) printf("No thread with the ID thread could be found.\n"); else if(ret == EINVAL) { printf("thread is not a joinable thread or Another thread is already waiting to join with this thread\n"); } return 0;}上面的程序的输出结果如下所示:
$ ./join.outthread is not a joinable thread or Another thread is already waiting to join with this thread在上面的程序当中我们在一个 detached 状态的线程上使用 pthread_join 函数 , 因此函数的返回值是 EINVAL 表示线程不是一个 joinable 的线程 。
在上面的程序当中 pthread_self() 返回当前正在执行的线程 , 返回的数据类型是 pthread_t , 函数 pthread_detach(thread) 的主要作用是将传入的线程 thread 的状态变成 detached 状态 。
我们再来看一个错误的例子 , 我们在一个无效的线程上调用 pthread_join 函数
#include <stdio.h>#include <error.h>#include <errno.h>#include <pthread.h>#include <unistd.h>pthread_t t1, t2;void* thread_1(void* arg) { int ret = pthread_detach(pthread_self()); sleep(2); if(ret != 0) perror(""); return NULL;}int main() { pthread_create(&t1, NULL, thread_1, NULL); sleep(1); int ret = pthread_join(t2, NULL); if(ret == ESRCH) printf("No thread with the ID thread could be found.\n"); else if(ret == EINVAL) { printf("thread is not a joinable thread or Another thread is already waiting to join with this thread\n"); } return 0;}上面的程序的输出结果如下:
$./oin01.outNo thread with the ID thread could be found.在上面的程序当中我们并没有使用 t2 创建一个线程但是在主线程执行的代码当中 , 我们使用 pthread_join 去等待他 , 因此函数的返回值是一个 EINVAL。
我们再来看一个使用 retval 例子:
#include <stdio.h>#include <pthread.h>#include <sys/types.h>void* func(void* arg){ pthread_exit((void*)100); return NULL;}int main() { pthread_t t; pthread_create(&t, NULL, func, NULL); void* ret; pthread_join(t, &ret); printf("ret = %ld\n", (u_int64_t)(ret)); return 0;}上面的程序的输出结果如下所示:
$./understandthread/join03.outret = 100
经验总结扩展阅读
- 十二星座是怎样解读爱情的
- 如何理解Java中眼花缭乱的各种并发锁?
- 十二星座中不适合异地恋的星座
- 2023年农历二月二十九出生的男孩命运和五行分析
- 2023年阴历五月初二日是封顶的好日子吗
- 2023年7月29日农历六月十二是乔迁最佳日期吗 2023年7月29日适不适合乔迁
- 2023年农历九月二十六能不能搬家入伙 农历二零二三年九月廿六能不能搬家
- 2023年农历九月二十七吉利吗 今天宜搬入新家吗
- 2023年农历九月二十八可以搬家吗 2023年农历九月二十八搬家怎么样
- 二宁是哪两个省