1. 函数介绍
- int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg) 线程创建函数
- thread,传出参数,用来接收线程id
- attr,线程属性设置
- start_routine,回调函数,告诉线程应该做的事情
- arg,回调函数的参数
- void pthread_exit(void *retval); 线程返回函数(若在子线程使用,可传递返回值,若在主线程中使用,可等待其他线程执行结束再释放进程资源)
- retval,传出参数,配合pthread_join接收子线程返回值
- int pthread_join(pthread_t thread, void **retval); 线程回收函数,阻塞,直到thread子线程执行结束
- thread,等待的子线程号
- retval,接收pthread_exit中的返回值
- int pthread_detach(pthread_t thread); 线程分离函数,将主线程与子线程分离,子线程资源不需要主线程调用pthread_join回收释放
- thread,分离的子线程号
- int pthread_cancel(pthread_t thread); 线程取消函数,主线程用于取消一个子线程,取消后子线程并不会立刻结束运行,而是等到子线程下一次执行系统调用时才会被kill
- thread,要取消的子线程号
2. 代码例程
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
struct Test
{
int num;
int age;
};
void *callback(void* arg)
{
for(int i=0; i<5; i++)
{
printf("子线程: i = %d\n", i);
//sleep(1);
}
printf("子线程: %ld\n", pthread_self());
((struct Test*)arg)->num = 100;
((struct Test*)arg)->age = 6;
pthread_exit(NULL);
}
int main()
{
pthread_t tid;
struct Test t;
pthread_create(&tid, NULL, callback, &t);
printf("主线程:%ld\n", pthread_self());
pthread_detach(tid);
pthread_exit(NULL); // 不会释放进程空间
return 0;
}
输出: