操作系统笔记 CH4 Threads

Dispatching is referred to as a thread. Resource of ownership is referred to as a process or task.

对进程的swapping和termination都牵扯它所有线程

线程是CPU使用的基本单位。由thread ID, program counter, register set, stack组成

multithreading models

User threads, supported above the kernel and are managed without kernel support.

Kernel threads, supported and managed directly by the operating system.

  • many-to-one

  • one-to-one

    一个线程阻塞,另一个还能运行

    并发。开销大。

    windows, linux, solaris 9

  • many-to-many

    用户线程映射到数量相同或更少的内核线程

    When a thread performs a blocking system call, the kernel can schedule another thread for execution.

    two-level model:

thread libraries

两种方法实现:1 在用户空间提供一个没有内核支持的库 2 由OS直接支持的内核级的库

  1. POSIX Pthreads

    Portable Operating System Interface of UNIX

    Referred to user-level library

  2. Win32 threads

    kernel-level threads library

  3. Java threads

    provides support at the language level for the creation and management of threads.

    两种创建线程的方法

    • extending thread class
    • define a class that implements the Runnable interface

thread issues

The fork() and exec() system calls

thread cancellation

Asynchronous cancellation 异步取消:立即取消

Deferred cancellation 延迟取消:不断检查是否该终止

signal handling

A signal is used in UNIX systems to notify a process that a particular event has occurred.

Synchronous signal: illegal memory access, division by 0.

Asynchronously signal: terminating a process with specific keystrokes, Ctrl+C ,由运行进程之外的事产生

two possible handlers:

  • a user-defined signal handler
  • a default signal handler, which is run by the kernel

同步信号送到需要发到产生它的线程

thread pools

优点:1 快 2 限制可用线程数量

thread-specific data

Thread-specific data allows each thread to have its own copy of data (Thread-local storage (TLS) ).

TLS visible across function invocations

scheduler activation

Scheduler activation – one scheme for communication between the user-thread library and the kernel.

provides upcalls, the kernel inform an application about certain events.

upcall handlers must run on a LWP.

当一个应用线程要阻塞,内核向应用程序发upcall,分配一个新LWP给应用线程,应用线程在这个LWP上运行upcall handler

当阻塞线程等待事件发生,内核向线程库发另一个upcall, kernel allocates a new LWP or preempt one of the user threads to run the upcall handler for this event.

OS examples

windows XP threads

one-to-one

ETHREAD (in kernel space), KTHREAD (in kernel space), TEB (in user space)

Linux threads - tasks

clone() system call


最后修改于 2020-02-28