(一)函数
-
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
功能:创建一个新的线程
参数:
thread 将新线程的id存储到这个地址空间里
attr NULL 使用缺省的属性
start_routine 函数指针 存放函数的入口地址 线程函数的入口地址
arg 传递给线程函数的唯一参数
返回值:
成功 0
错误 非0的错误码 errno被设置
Compile and link with -pthread.
void *(*start_routine) (void *) -
#include <pthread.h>
pthread_t pthread_self(void);
功能:获取当前线程的id
返回值:
返回当前线程的tid unsigned long -
#include <pthread.h>
void pthread_exit(void *retval);
功能:终止当前线程
参数:
retval 将该指针的值传递给进程中调用pthread_join(3)的另外一个线程,所以接收该值时,用二级指针作为形参接收 -
#include <pthread.h>
int pthread_detach(pthread_t thread);
功能:分离一个线程
参数:
thread 指定要被分离的线程的id
返回值:
成功 0
错误 非0的错误码
如果将线程设置为分离状态,线程终止的时候,自动将资源释放给系统 -
#include <pthread.h>
int pthread_join(pthread_t thread, void **retval);
功能:阻塞等待汇合一个线程,等该线程终止
参数:
thread 指定了要汇合的线程的tid 线程必须是可汇合的线程
retval 将可汇合线程的退出状态码拷贝到retval中.
如果可汇合的线程是取消的线程.将PTHREAD_CANCELED拷贝到retval中
返回值:
成功 0
错误 非0的错误码
汇合:一个线程(这个线程必须是可汇合的线程)终止以后,同一个进程中的另外一个线程回收终止线程的资源 -
#include <pthread.h>
int pthread_cancel(pthread_t thread);
功能:给指定的线程发送取消请求
参数:
thread 指定要取消的线程的id
返回值:
成功 0
错误 非0的错误码
(二)代码
#include <t_stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
void *thr_func1(void *arg){
printf("thr_func1 running...\n");
return (void *)1l;
}
void *thr_func2(void *arg){
printf("thr_func2 running...\n");
pthread_exit((void *)2l);
}
void *thr_func3(void *arg){
while(1){
printf("thr_func3 running...\n");
sleep(1);
}
return NULL;//永远不可能执行到
}
int main(void){
void *ret;
//创建一个新的线程
pthread_t tid;
pthread_create(&tid, NULL, thr_func1, NULL);
//阻塞等待新线程的终止,汇合新线程
//将新线程的退出状态码(或返回值)保存到ret中
pthread_join(tid, &ret);
printf("thr_func1 exit code...%ld\n", (long)ret);
//创建一个新的线程
pthread_create(&tid, NULL, thr_func2, NULL);
//阻塞等待新线程的终止,汇合新线程
//将新线程的退出状态码(或返回值)保存到ret中
pthread_join(tid, &ret);
printf("thr_func2 exit code...%ld\n", (long)ret);
//创建一个新的线程
pthread_create(&tid, NULL, thr_func3, NULL);
sleep(5);
//给指定tid的线程发出取消请求
pthread_cancel(tid);
//阻塞等待新线程的终止,汇合新线程
//将新线程的退出状态码(或返回值)保存到ret中
pthread_join(tid, &ret);
if(ret == PTHREAD_CANCELED)
printf("thr_func3 exit code...%ld\n", (long)ret);
return 0;
}