OS Review Chapter 5: Thread

OS Review Chapter1: Introduction
OS Review Chapter 2: Computer-System Structures
OS Review Chapter 3: Operating-System Structures
OS Review Chapter 4: Process

Chapter 5 Thread

What is a thread?–A thread, also known as lightweight process (LWP),is a basic unit of CPU execution.

A thread has a thread ID, a program counter, a register set, and a stack–similar to a process

**However, a thread shares with other threads in the same process its code section, data section, and other OS resources (e.g., files and signals). **

在這裏插入圖片描述

同一個進程的多個線程共享該進程的其他資源(不包括CPU、寄存器、棧)

Linux中不存在線程進程的概念,同一稱作task

Thread Usage

在這裏插入圖片描述

Benefits

  • Responsiveness
  • Resource Sharing (進程之間資源共享需要調用系統調用,需要頻繁切換到kernel)
  • Economy (創建時的開銷)
  • Utilization of MP(multi processors) Architectures

User Threads

Thread management done by user-level threads library --POSIX Pthreads

用戶線程阻塞會導致該進程的其他線程阻塞,kernel不知道process中的其他thread,認爲這個process是阻塞的。 if one thread is blocked, every other threads of the same process are also blocked because the containing process is blocked.

User threads are supported at the user level. The kernel is not aware of user threads.

A library provides all support for thread creation, termination, joining, and scheduling. There is no kernel intervention, and, hence, user threads are usually more efficient.

在這裏插入圖片描述

Kernel Threads

Kernel threads are directly supported by the kernel. The kernel does thread creation,termination, joining, and scheduling in kernel space.

Kernel threads are usually slower than the user threads.

通常是用戶創建一個kernel thread,導致kernel需要進行系統調用陷入內核,創建完成後返回用戶態

However, blocking one thread will not cause other threads of the same process to block. The kernel simply runs other threads.

In a multiprocessor environment, the kernel can schedule threads on different processors

Multithreading Models

Many-to-One

多對一模型:多個用戶級線程線程映射到一個內核級線程。每個用戶進程只對應一個內核級線程。
優點:用戶級線程的切換在用戶空間即可完成,不需要切換到核心態,線程管理的系統開銷小,效率高。
缺點:當一個用戶線程阻塞後,整個進程就會都阻塞,併發度不高。多個線程不可在多處理機上並行運行。

One-to-One

一個用戶進程對應一個內核進程。每個用戶有與內核進程相同數量的用戶進程。
優點:當一個線程被阻塞後,另外的線程還可以繼續執行,併發性強。多線程可在多核處理機上併發執行
缺點:一個用戶線程會佔用多個內核級線程,線程切換是需要將用戶態轉換爲核心態,因此線程管理的成本高,開銷大。

Many-to-Many

Allows many user level threads to be mapped to many kernel threads. Allows the operating system to create a sufficient number of kernel threads.

多對多模型:n個用戶級線程映射到m個內核級線程(n>=m)。每個用戶進程對應m個內核級線程。
克服了多對一模型併發度不高的缺點,又克服了一對一模型中一個用戶進程佔用太多內核級線程,開銷太大的缺點。

Threading Issues

Semantics of fork() and exec() system calls. ???

Thread cancellation.

  • Asynchronous cancellation terminates the target thread immediately (實現過程簡單)
  • **Deferred cancellation **allows the target thread to periodically check if it should be cancelled :The point a thread can terminate itself is a cancellation point(延遲,安全撤銷)

Pthread supports deferred cancellation.

With asynchronous cancellation, if the target thread owns some system-wide resources, the system may not be able to reclaim all recourses.

But for deferred cancellation,Reclaiming resources is not a problem.

Signal Handling

Thread Pools

Create a number of threads in a pool where they await work .

通常線程池中的線程數目是adaptive(自適應的)

Advantages:

◆Usually slightly faster to service a request with an existing thread than create a new thread

◆Allows the number of threads in the application(s) to be bound to the size of the pool

Solaris 2 Threads

M:M

在這裏插入圖片描述

Windows XP Threads

Implements the one-to-one mapping.

Each thread contains

  • a thread id -
  • register set
  • separate user and kernel stacks
  • private data storage area

在這裏插入圖片描述

TEB: Thread Enviroment Block

Linux Threads

linux中的進程已經十分高效,引入線程作爲資源共享的一個手段

Linux refers to them as tasks rather than threads.

Thread creation is done through clone() system call. Clone() allows a child task to share the address space of the parent task (process)

Windows Thread APIs

  • CreateThread
  • GetCurrentThreadId - returns global ID
  • GetCurrentThread - returns handle
  • SuspendThread/ResumeThread
  • ExitThread
  • TerminateThread
  • GetExitCodeThread
  • GetThreadTimes

Example:

#include <iostream>
#include<Windows.h>
#include<synchapi.h>
BOOL thrdDone = FALSE;
using namespace std;

DWORD WINAPI Fibonacci()
{
    int num;
    cin >> num;
    int a = 1;
    int b = 1;
    int n = a+b;
    for (int i = 0; i < num; i++)
    {
        cout << i+1<<" : "<<a << endl;
        a = b;
        b = n;
        n = a + n;
    }
    thrdDone = TRUE;
    return 0;
}

int main()
{
    cout << "enter the number of the Fibonacci:  " <<endl;
    HANDLE hThread;
    hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Fibonacci, NULL, 0, NULL);
    //getchar();
    while (!thrdDone);
    DWORD dw=WaitForSingleObject( hThread, 1000);
    //cout << dw;
    //std::cout << "Hello World!\n";
    system("pause");
}

Example Explained: Main thread is process When process goes, all threads go Need some methods of waiting for a thread to finish

Threads states

pthread threads have two states

◆joinable and detached

threads are joinable by default

◆Resources are kept until pthread_join

◆can be reset with attribute or API call

detached thread can not be joined

◆resources can be reclaimed at termination

◆cannot reset to be joinable

#include <stdio.h>
#include <pthread.h>

#define MAX_SEQUENCE 100

//一組數據,用於創建線程時作爲參數傳入
struct Data{
     int num; //斐波那契數列的項數
     int Fibo[MAX_SEQUENCE];//最大容量,斐波那契數列
};

void *Fibonacci(void *data){//獲得斐波那契數列
    struct Data *tmp = (struct Data*)data;//轉化爲實際類型
    int i;

    if(  tmp->num == 0 ){
        printf("error!enter a number larger than 0");
    }
    if( tmp->num == 1 ){
        tmp->Fibo[0] = 0;
    }
    tmp->Fibo[0] = 0;
    tmp->Fibo[1] = 1;

    for( i=2; i < tmp->num; i++ ){
        tmp->Fibo[i] = tmp->Fibo[i-1] + tmp->Fibo[i-2]; 
    }
 }

int main(){
    struct Data data;
    pthread_t th;//線程標識符
    int ret; //pthread的返回值 ret = 0,創建線程成功
    int n;
    int i;

    printf("The fibonacci produce programe!\nPlease input an number within 1~200: ");
    scanf("%d", &n);
    if(n < 0 || n > 200){
        printf("Your input is error.");
        return -1;
    }
    data.num = n;//賦值


    //create a thread
    ret = pthread_create(&th, NULL, Fibonacci, (void *)&data);
    if( ret != 0 ){
        printf("Create thread error!\n");
        return -1;
    }

    //阻塞調用線程
    pthread_join( th, NULL);

    //輸出斐波那契數列
    if( data.num == 0){
        printf("Nothing output.");
    }
    else{
	    for(int i=0;i<n;i++){
        printf("The Fibonacci items are:  ");
	printf("%d\n",data.Fibo[i]);
	    }
        }
        printf("\n");
 }

Context

OS Review Chapter1: Introduction
OS Review Chapter 2: Computer-System Structures
OS Review Chapter 3: Operating-System Structures
OS Review Chapter 4: Process

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章