多线程编程全解析:从基础到调度
1. 多线程编程基础
多线程编程在现代软件开发中扮演着至关重要的角色,它允许程序同时执行多个任务,提高了程序的性能和响应能力。在 Linux 系统中,POSIX 线程 API(pthreads)是实现多线程编程的标准接口,它最早在 IEEE POSIX 1003.1c 标准(1995 年)中被定义,并作为 C 库的一部分(libpthread.so)实现。
过去 15 年左右,pthreads 有两种实现:LinuxThreads 和 Native POSIX Thread Library(NPTL)。NPTL 更符合规范,特别是在信号处理和进程 ID 处理方面,现在它占据主导地位,但在一些旧版本的 uClibc 中仍可能使用 LinuxThreads。
2. 创建新线程
创建线程的函数是 pthread_create(3)
,其原型如下:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
该函数创建一个新的执行线程,线程从 start_routine
函数开始执行,并将线程描述符存储在 thread
指向的 pthread_t
变量中。新线程继承调用线程的调度参数,但可以通过 attr
指针