phread_create,phread_jion,phread_detach 布满荆棘的人生 2023-07-25 05:26 96阅读 0赞 环境:windows10 linux子系统ubuntu 工具:gcc 三个函数的头文件:pthread.h 头文件: 系统标准头文件位置:/usr/include 安装库的头文件位置:/usr/local 库文件: 系统标准库文件位置:/lib /usr/lib 用户安装库文件位置:/usr/local/lib ![在这里插入图片描述][2020041222450283.png] 可以看到usr和local的目录结构基本类似 find ./local -name “*pthread*” ![在这里插入图片描述][20200412223955711.png] 可以看到线程相关函数是系统自带的 #### pthread\_create #### 原型: find /usr/include/ -name “*pthread*” | xargs grep -En “pthread\_create” /usr/include/pthread.h /* Create a new thread, starting with execution of START-ROUTINE getting passed ARG. Creation attributed come from ATTR. The new handle is stored in *NEWTHREAD. */ extern int pthread_create (pthread_t *__restrict __newthread, // 线程句柄 const pthread_attr_t *__restrict __attr, // 线程属性,默认null void *(*__start_routine) (void *), // 线程的运行的主体函数 void *__restrict __arg) __THROWNL __nonnull ((1, 3)); // 线程函数的入参 函数的后缀后续如果探究再做补充 <font color=red>函数的后缀后续如果探究再做补充</font> pthread\_create和joinable: linux下线程有joinable和unjoinable两种属性,默认是joinable的属性,可以在创建的时候指定。 1.joinable属性时候,线程结束或者是pthread\_exit后不会主动释放相关资源(程所占用堆栈和线程描述符,总计8K多)。只有调用pthread\_jion函数后才会释放掉。 2.unjoinable属性时候,线程结束后会自动释放这些资源。 资源的占用和释放后续再用代码验证下 创建的线程共享所在进程的全局资源,拥有各自的局部资源。 #### pthread\_join #### 原型: /* Make calling thread wait for termination of the thread TH. The exit status of the thread is stored in *THREAD_RETURN, if THREAD_RETURN is not NULL. This function is a cancellation point and therefore not marked with __THROW. */ extern int pthread_join (pthread_t __th, void **__thread_return); 阻塞线程函数,等待线程函数执行完才可以执行后续代码,获取线程的执行结果。 应该是create时候设置为null或者joinable时候可以使用。今天太晚了,后面写代码验证。设置为unjoinable时候表现如何也值得探究下。 #### pthread\_detach #### 原型: /* Indicate that the thread TH is never to be joined with PTHREAD_JOIN. The resources of TH will therefore be freed immediately when it terminates, instead of waiting for another thread to perform PTHREAD_JOIN on it. */ extern int pthread_detach (pthread_t __th) __THROW; 分离线程函数。让线程自己跑,不关注线程的执行结果,也不等待线程的结束。 今天没时间跑代码了,后面继续完善 [2020041222450283.png]: /images/20230528/6e6920cb629d4211a8c799c39a7287a9.png [20200412223955711.png]: /images/20230528/190f0fc1b8e8468880b10d892b1af959.png
还没有评论,来说两句吧...