- 殺死線程的函數
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申請的內存可以被其他線程釋放