1 线程概念
所谓线程,就是操作系统所能调度的最小单位。普通的进程,只有一个线程在执行对应的逻辑。我们可以通过多线程编程,使一个进程可以去执行多个不同的任务。相比多进程编程而言,线程享有共享资源,即在进程中出现的全局变量,每个线程都可以去访问它,与进程共享内存空间,使得系统资源消耗减少。
2
2.1 安装
Ubuntu默认是没有pthread库的,需要安装。输入命令:
$ sudo apt-get install -y glibc-doc manpages-posix-dev
2.2获取线程号
#include <pthread.h>
pthread_t pthread_self(void);
2.3
创建线程
int pthread_create(
pthread_t *restrict tidp, //新创建的线程ID指向的内存单元。
const pthread_attr_t *restrict attr, //线程属性,默认为NULL
void *(*start_rtn)(void *), //新创建的线程从start_rtn函数的地址开始运行
void *restrict arg //默认为NULL。若上述函数需要参数,将参数放入结构中并将地址作为arg传入。
);
int pthread_create(
pthread_t *thread,
const pthread_attr_t *attr