一、多线程概述
在多处理器或多核系统中,可以通过并行处理提升速度。开线程相比于开进程的开销更低,因为在进程中创建线程不会涉及初始化新的虚拟内存空间以及为进程创建环境,进程内所有的线程共享相同的虚拟地址空间。
Thread operations include thread creation, termination, synchronization (joins,blocking), scheduling, data management and process interaction.
A thread does not maintain a list of created threads, nor does it know the thread that created it.
All threads within a process share the same address space.
Threads in the same process share:
- Process instructions
- Most data
- open files (descriptors)
- signals and signal handlers
- current working directory
- User and group id
Each thread has a unique:
- Thread ID
- set of registers, stack pointer
- stack for local variables, return addresses
- signal mask
- priority
- Return value: errno
参考资料:https://www.cs.cmu.edu/afs/cs/academic/class/15492-f07/www/pthreads.html
二、基本操作
2.1 POSIX thread库支持C/C++的API , 为Unix系统支持的线程操作
pthread_create
//@param thread: returns the thread id.
//@param attr : Set to NULL if default thread attributes are used, else define members of the struct pthread_attr_t defined in bits/pthreadtypes.h
//@param void * (*start_routine) : pointer to the function to be threaded. Function has a single argument: pointer to void.
//@param *arg - pointer to argument of function. To pass multiple arguments, se