4.1 Provide two programming examples in which multithreading does not provide better performance than a single-threaded solution

例子:多线程交替写入一个文件,由于要用锁,算上上下文切换,比单线程更慢。

例子 2:没有绑定核心,导致在内核之间调度,性能变差。

4.2 Describe the actions taken by a thread library to context switch between user-level threads.

  1. 将所有寄存器备份到线程控制块(TCB)
  2. 还原下一个线程的状态
  3. 执行下一个线程

4.3 Under what circumstances does a multithreaded solution using multiple kernel threads provide better performance than a single-threaded solution on a single-processor system?

例子:对于非计算密集型的程序,大量时间是在等待外设 IO 操作(如磁盘复制、页面调度),使用多线程可以提高 CPU 的利用率。

4.4 Which of the following components of program state are shared across threads in a multithreaded process?

a. Register values

b. Heap memory

c. Global variables

d. Stack memory

答:堆内存和全局变量。

4.5 Can a multithreaded solution using multiple user-level threads achieve better performance on a multiprocessor system than on a single-processor system?

用户级线程位于用户空间,对于内核而言并不知道他是多线程的,因此只可能在一个核心运行。

The program shown in Figure 4.11 uses the Pthreads API. What would be output from the program at LINE C and LINE P?

image-20211025210426761

子进程的全局变量不能和父进程共享。所以值是 5,0

4.8 Consider a multiprocessor system and a multithreaded program written using the many-to-many threading model. Let the number of user-level threads in the program be more than the number of processors in the system. Discuss the performance implications of the following scenarios.

a. The number of kernel threads allocated to the program is less than the number of processors.

b. The number of kernel threads allocated to the program is equal to the number of processors.

c. The number of kernel threads allocated to the program is greater than the number of processors but less than the number of user-level threads.

a. 内核线程会各自在核心运行,可能存在空闲的核心。

b. 核心完全利用,除非发生阻塞。

c. 核心完全利用,多余的线程在内核之间调度运行。