- 杀死线程的函数
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. 线程分离函数
```cpp
int 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_DETACHED
Threads that are created using attr will be created in a detached state.
PTHREAD_CREATE_JOINABLE
Threads 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申请的内存可以被其他线程释放