linux线程学习初步02
生活随笔
收集整理的這篇文章主要介紹了
linux线程学习初步02
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
代碼案例:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h>void* thr(void *arg) {while(1) {printf("I am a common thread\n");sleep(1);}return 100; }int main() {pthread_t ptid;pthread_create(&ptid, NULL, thr, NULL);sleep(5);void *ret;pthread_cancel(ptid);int num = pthread_join(ptid, &ret);printf("num = %d, ret = %d\n",num , (int)ret);return 0; } ``2. 線程分離函數```cppint pthread_detach(pthread_t thread);使用了線程分離函數, 該線程不用再被
pthread_join函數回收資源
代碼案例:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <string.h>void* thr(void *arg) {printf("I am a common thread 1\n");sleep(3);printf("I am a common thread 1-\n");return (void *)100; }int main() {pthread_t ptid;pthread_create(&ptid, NULL, thr, NULL);pthread_detach(ptid);sleep(4);int ret = pthread_join(ptid, NULL);printf("ret = %d error is %s\n",ret, strerror(ret));return 0; }線程id在進程內部是唯一的, 但是在整個操作系統中不是唯一的
設置線程分離
int pthread_attr_setdetachstate(pthread_attr_t *attr, int detachstate); 參數介紹:attr:init初始化的屬性detachstate:PTHREAD_CREATE_DETACHEDThreads that are created using attr will be created in a detached state.PTHREAD_CREATE_JOINABLEThreads that are created using attr will be created in a joinable state.int pthread_attr_getdetachstate(const pthread_attr_t *attr, int *detachstate);發現,設置成為線程分離后, 主線程如果先執行完了, 子線程沒有機會執行
代碼案例:
getconf GNU_LIBPTHREAD_VERSION 查看版本
注意事項:
被join線程可能在join函數返回前,就釋放完自己所有的內存資源,所以不應當回收線程棧中的值
malloc和mmap申請的內存可以被其他線程釋放
總結
以上是生活随笔為你收集整理的linux线程学习初步02的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: dnf49级刷什么图经验最多
- 下一篇: 鲜花朵朵剧情介绍