linux 线程
线程的概念
- 1、线程是进程内部的一个执行分支,线程量级很小。(所谓的内部就是在进程的地址空间内运行)
- 2、一切进程至少都有一个线程
线程和进程的区别
- 进程是资源竞争的基本单位
- linux下没有真正意义的线程,因为linux下没有给线程设计专有的结构体,它的线程是用进程模拟的,而它是由多个进程共享一块地址空间而模拟得到的。
- 创建一个线程的资源成本小,工作效率高
- Linux下cpu所看到的所以进程都可以看成轻量级的进程
- 进程是承担分配系统资源的基本实体,进程具有独立性(但进程间通信打破了独立性)
- 线程是cpu或操作系统调度的基本单位,线程具有共享性
线程共享的资源
- 同一块地址空间
- 数据段
- 代码段
- 堆区
- 动态库加载区
线程独立的资源
- 线程会产生临时变量,临时变量保存再栈上,所以每个线程都有自己的私有栈结构
- 每个线程都有私有的上下文信息。
- 线程ID
- 一组寄存器的值
- errno变量
- 信号屏蔽字以及调度优先级
查看线程的LWP号(线程号)
- 找到进程ID(pid)
- ps -Lf pid
创建线程
pthread_create函数
int pthread_create( pthread_t *thread, //线程ID const pthread_attr_t *attr, //线程属性 void *(*start_routine)(void *), //线程处理函数 void *arg //线程处理函数参数 )
//返回值:若成功则返回0,否则返回出错编号
创建一个子线程:
#include <stdio.h> #include <unistd.h> #include <pthread.h> void *myfunc(void * arg) { printf("child thread id: %lu ", pthread_self()); return NULL; } int main(int argc, const char* argv[]) { pthread_t pthid; pthread_create(&pthid, NULL, myfunc, NULL); printf("parent thread id: %lu ", pthread_self()); printf("xmm "); sleep(2); return 0; }
循环创建多个子线程:
#include <stdio.h> #include <unistd.h> #include <pthread.h> void *myfunc(void * arg) { int num = (int)arg; printf("child thread %d id: %lu, ", num, pthread_self()); return NULL; } int main(int argc, const char* argv[]) { pthread_t pthid[5]; int i; for(i=1; i<=5; i++) { pthread_create(&pthid[i], NULL, myfunc, (void*)i); } printf("parent thread id: %lu ", pthread_self()); printf("xmm "); sleep(2); return 0; }
打印错误信息:
int ret = pthread_create(&pthid, NULL, myfunc, NULL); if(ret != 0) { printf("%s ", strerror(ret)); }