!!!Chapter 4 Multithread Programming

来源:互联网 发布:魔客吧还原数据密码 编辑:程序博客网 时间:2024/05/21 19:46

A thread is a fundamental unit of CPU utilization that forms the basis of multithreaded computer systems.

A thread is a flow of control within a process. A multithreaded process contains several different flows of control within the same address space.

4.1 Overview

A thread is a basic unit of CPU utilization; it comprises a thread ID, a program counter, a register set, and a stack. It shared with other threads belonging to the same process its code section, data section, and other operating-system resources, such as open files and signals.

4.1.2 Benefits

1. Responsiveness. A web browser can display large image while response user action

2. Resource sharing. Threads share the memory and resources of the process to which they belong by default.

3. Economy. Allocating memory and resources for process is costly.

4. Scalability. Multithreading on a multi-CPU machine increases parallelism.

4.1.3 Multicore Programming

In general, five areas present challenges in programming for multicore systems:

1. Dividing activities.

2. Balance

3. Data splitting

4. Data dependency. In instance where one task depends on data from another, programmers must ensure that the execution of the tasks is synchronized to accommodate the data dependency.

5. Testing and debugging

4.2 Multithreading Models

Support for threads may be provided either at the user level, for user threads, or by the kernel, forkernel threads.

Ultimately, a relationship must exist between user threads and kernel threads.

4.2.1 Many-to-One Model

+ it is efficient

- the entire process will block if a thread makes a blocking system call.

- multiple threads are unable to run in parallel on multiprocessors.

4.2.2 One-to-One Model

+ allowing another thread to run when a thread makes a blocking system call

+ allows multiple threads to run in parallel on multiprocessors

- creating a user thread requires creating the corresponding kernel thread => number of threads is limited

Linux and Windows use this model.

4.2.3 Many-to-Many Model

+ developers can create as many threads as necessary

+ corresponding kernel threads can run in parallel on a multiprocessor

4.3 Thread Libraries

A thread library provides the programmer with an API for creating and managing threads.

Three main thread libraries are in use today: 1.POSIX Pthreads, 2.Win32, 3.Java.

4.3.1 Pthreads

Pthreads refers to the POSIX standard defining an API for thread creation and synchronization. This is a specification for thread behavior, not animplementation.

#include <stdio.h>#include <pthread.h>int sum;      // global variable shared between threadsvoid *runner(void *param);       // the child threadint main(int argc, char *argv[])    // pass one parameter to add sum{    pthread_t tid;                  // thread id    pthread_attr_t attr;            // set of attributes for the thread        pthread_attr_init(&attr);       // init attr with default value    // create a new thread, the 1st parameter is thread id, 2nd is attribute     // 3rd is the new function, 4th is the parameter of that function    pthread_create(&tid, &attr, runner, argv[1]);    pthread_join(tid, NULL);        // wait for the thread to exit    printf("%d\n", sum);     }// the new thread will begin control in this functionvoid *runner(void *param){    int i, upper = atoi(param);    sum = 0;        for (i = 1; i <= upper; ++i) {        sum += i;    }    pthread_exit(0);}

4.4 Threading Issues

4.4.1 The fork() and exec() System Calls

fork() is used to create a separate, duplicate process, when one thread in a program calls fork(), the new process can:

1. duplicate all threads

2. be single-threaded

exec() system call typically works in the same way. If a thread invokes exec() system call, the program specified in the parameter to exec() will replace the entire process --- including all threads.

4.4.2 Cancellation

Thread cancellation is the task of terminating a thread before it has completed.

A thread that is to be canceled is often referred to as the target thread.

Cancellation of a target thread may occur in two different scenarios:

1. Asynchronous cancellation. One thread immediately terminate the target thread.

2. Deferred cancellation. The target thread periodically checks whether it should terminate.

4.4.3 Signal Handling

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

All signals follow the same pattern:

1. A signal is generated by the occurrence of a particular event.

2. A generated signal is delivered to a process.

3. Once delivered, the signal must be handled.

synchronous signals are generated and received by the same process. asynchronous signals is generated by an event external to the receiver process.

A signal may be handled by one of two possible handlers:

1. A default signal handler

2. A user-defined signal handler

Every signal has a default signal handler that is run by the kernel when handling that signal. The default action can be overridden by auser-defined signal handler that is called to handle the signal.

Because signals need to be handled only once, a signal is typically delivered only to the first thread found that is not blocking it.

4.4.4 Thread Pools

Thread pool is used to create a number of threads at process startup and place them into a pool, where they sit and wait for work.

Thread pools offer these benefits:

1. Servicing a request with an existing thread is usually faster than waiting to create a thread.

2. A thread pool limits the number of threads that exist at any one point.

4.4.5 Thread-Specific Data

In some circumstances, each thread might need its own copy of certain data. We will call such datathread-specific data.

4.4.6 Scheduler Activations

Multithreaded programs may concern communication between the kernel and the thread library, which may be required by many-to-many and two-level models.

4.5 OS Samples => Linux Threads   P 173














原创粉丝点击