日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

linux线程学习初步02

發布時間:2023/11/30 linux 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 linux线程学习初步02 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
  • 殺死線程的函數
  • int pthread_cancel(pthread_t thread); 參數介紹:需要輸入的tid 返回值:識別返回 errno成功返回 0 被殺死的線程,退出狀態值為一個 #define PTHREAD_CANCELED((void *)-1)

    代碼案例:

    #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_equal(pthread_t t1, pthread_t t2);

    線程id在進程內部是唯一的, 但是在整個操作系統中不是唯一的

  • 線程屬性設置
  • 初始化線程屬性 int pthread_attr_init(pthread_attr_t *attr);銷毀線程屬性 int pthread_attr_destroy(pthread_attr_t *attr);

    設置線程分離

    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);

    發現,設置成為線程分離后, 主線程如果先執行完了, 子線程沒有機會執行
    代碼案例:

    nclude <unistd.h> #include <pthread.h> #include <string.h>void* thr(void *arg) {sleep(2);printf("I am a common thread 1\n");return (void *)100; }int main() {pthread_attr_t attr;pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);pthread_t ptid;pthread_create(&ptid, &attr, thr, NULL);printf("I am a main thread\n");pthread_attr_destroy(&attr);pthread_exit(NULL);// 如果不加這句話,自線程沒有機會打印 }

    getconf GNU_LIBPTHREAD_VERSION 查看版本

    注意事項:
    被join線程可能在join函數返回前,就釋放完自己所有的內存資源,所以不應當回收線程棧中的值

    malloc和mmap申請的內存可以被其他線程釋放

    總結

    以上是生活随笔為你收集整理的linux线程学习初步02的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。