9.线程
-
概念:轻量级的进程(lwp),一个进程内部可以有多个线程,默认情况下一个进程只有一个线程
- 线程是最小的执行单位,进程是最小的系统资源分配单位:工人与工厂的关系
- 内核都是通过clone函数实现
- 线程也有自己的进程控制块(PCB Process Control Block)
-
线程
man page
安装sudo apt-get install manpages-posix-dev
-
shell端查看lwp号:
ps -Lf pid
-
每个线程也有自己的errno:
- 查看errno:
char *strerror(int erronum);
- 查看errno:
-
线程相关函数调用库:
#include <pthread.h>
-
线程程序编译:
gcc filename -lpthread
-
相关函数
- 线程创建:
pthread_create()
:int pthread_create(pthread_t *thread,const pthread_attr_t *attr,void *(*start_rountine)(void *),void *arg);
thread
:线程的id。传出参数attr
:代表线程的属性- 第三个参数,函数指针
arg
:线程执行函数的参数- 返回值
- 成功返回0
- 失败返回
errono
e.g.
#include <stdio,h> #include <unistd.h> #include <pthread.h> //子线程 void* thr(void *arg) { printf("i am a thread,pid=%d,tid=%lu\n",getpid(),pthread_self()); return NULL; } int mian() { pthread_t tid; pthread_create(&tid,NULL,thrm,NULL); printf("i am main pthread,pid=%d,tid=%lu",getpid(),pthread_self()); sleep(1);//保证子线程运行了 return 0; }
-
线程退出函数:
void pthread_exit(void *retal);
- 在线程中使用
pthread_exit()
return
:主线程不能使用,不然全退出exit(1)
:也不能使用,也是全推=退出
- 在线程中使用
-
线程回收:
int pthread_join(pthread_t thread,void ** retval);
- 阻塞等待回收
thread
:创建的时候传出的第一个参数retval
:代表传出线程的退出信息
e.g.
#include <stdio,h> #include <unistd.h> #include <pthread.h> //子线程 void* thr(void *arg) { printf("i am a thread,pid=%d,tid=%lu\n",getpid(),pthread_self()); return NULL; } int mian() { pthread_t tid; pthread_create(&tid,NULL,thrm,NULL); printf("i am main pthread,pid=%d,tid=%lu",getpid(),pthread_self()); void *ret; pthread_join(tid,&ret); sleep(1);//保证子线程运行了 return 0; }
-
杀死进程:
pthread_cancel
int pthread_cancel(pthread_t thread);
thread
:线程id- 返回值
- 成功返回0
- 失败返回
errno
- 线程创建:
-
线程分离:
pthread_detach
int pthread_detach(pthread_t thread);
- 此时此线程不需要
pthread_join()
回收
- 此时此线程不需要
-
进程属性控制
-
初始化线程属性
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
线程分离PTHREAD_CREATE_JOINABLE
允许回收
-
e.g.
#include <stdio.h> #include <unistd.h> #include <pthread.h> #include <string.h> void *thr(void *arg){ printf("i am a thread \n"); return NULL; } int main() { pthread_attr_t attr; pthread_attr_init(&attr);//初始化属性 pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); pthread_t tid; pthread_create(&tid,&attr,thr,NULL);//创建线程 int ret; if((ret = pthread_join(tid,NULL))>0){//如果没有需要回收的线程 printf("join err:%d,%s\n",ret,strerror(ret)); } pthread_attr_destroy(&attr);//销毁属性 return 0; }
-
-
其他
- 查看线程库版本
getconf GNU_LIBPTHREAD_VERSION
- 创建多少个线程合适:
- cpu核数*2+2
- 用于科学计算的就是cpu核数*2
- 查看线程库版本