PDF 及笔记:
电脑上如果 PDF 不展示或者展示不正常,使用 Chrome 并安装 PDF Viewer 插件。其他情况请下载文件查看:tlpi-ch29。
POSIX 标准定义了一套线程机制和 API 标准,称为 pthread。
Linux 实现了 pthread 标准,该实现被称为 NPTL(Native POSIX Threads Library)。旧的 Linux 版本的实现为 LinuxThreads,目前已不主流。
一般系统调用的 API,其返回值为 0 表示成功、-1 表示失败;具体失败原因从 errno 中取。
pthread API 不同,0 表示成功,正整数表示失败,且其值同 errno 定义的一致。
不同线程拥有自己的 errno。在 Linux 上,读取 errno 实际上是通过一段 macro 将其转化为一个函数调用(而不是读一个全局变量)。
Besides global memory, threads also share a number of other attributes (i.e., these attributes are global to a process, rather than specific to a thread). These attributes include the following:
- process ID and parent process ID;
- process group ID and session ID;
- controlling terminal;
- process credentials (user and group IDs);
- open file descriptors;
- record locks created using fcntl(); z signal dispositions;
- file system–related information: umask, current working directory, and root directory;
- interval timers (setitimer()) and POSIX timers (timer_create());
- System V semaphore undo (semadj) values (Section 47.8);
- resource limits;
- CPU time consumed (as returned by times());
- resources consumed (as returned by getrusage()); and
- nice value (set by setpriority() and nice()).
Among the attributes that are distinct for each thread are the following:
- thread ID (Section 29.5);
- signal mask;
- thread-specific data (Section 31.3);
- alternate signal stack (sigaltstack());
- the errno variable;
- floating-point environment (see fenv(3));
- realtime scheduling policy and priority (Sections 35.2 and 35.3);
- CPU affinity (Linux-specific, described in Section 35.4);
- capabilities (Linux-specific, described in Chapter 39); and
- stack (local variables and function call linkage information)
- The thread’s start function performs a return specifying a return value for the thread.
- The thread calls pthread_exit() (described below).
- The thread is canceled using pthread_cancel() (described in Section 32.1).
- Any of the threads calls exit(), or the main thread performs a return (in the main() function), which causes all threads in the process to terminate immediately
值得注意的是最后一种方式,无论哪个线程调用了 exit()
,整个程序、所有线程都会马上结束。
调用完 pthread_create() 后,操作系统并不保证马上调度到该线程运行。
线程执行完后,其返回值(一般是指针)不该指向线程的栈。因为这块内存区域在线程结束后会被 OS 回收利用。
线程间等待结束和回收资源 pthread_join()
与进程间 waitpid()
不同之处:
pthread_join()
等待其他任意进程结束;进程间则需要是父进程回收子进程章末总结的线程与进程对比,是本章的 重点。