12th Chapter Concurrent Programming
12.1 Process-based concurrency programming
The simplest way to construct a concurrency program--with process
Common functions are as follows:
"Process-based concurrent server"
- Use the SIGCHLD handler to reclaim the resources of the zombie child process.
- The parent process must close their respective CONNFD copies (attached descriptors) to avoid memory leaks.
- The connection to the client terminates because the reference count in the socket's file table entry is until the CONNFD of the parent-child process is closed.
"Concurrent programming based on I/O multiplexing"
Using the Select function requires the kernel to suspend the process and return control to the application only after one or more I/O events have occurred.
int select (int n,fd_set *fdset,null,null,null); Returns the number of non-0 of the prepared descriptor, or 1 if there is an error.
"Concurrent event-driven server based on I/O multiplexing"
State machine: A set of states, input events, output events, and transitions.
Self-loop: the transfer between the same input and output states.
The pros and cons of I/O multiplexing technology
Compared to the process-based design gives the programmer more control over the process behavior, running in a single process context, each logical flow can access all the address space, sharing data between the stream is easy.
Coding is complex, and complexity increases as the number of concurrent granularity decreases. Granularity: The number of instructions executed per time slice per logical stream.
12.3 Thread-based concurrency programmingPOSIX Threads
POSIX threads are a standard interface for processing threads in the C language, allowing programs to create, kill, and reclaim threads that share data securely with peer threads.
The code of the thread and the local data are encapsulated in a thread routine,
Creating Threads
Threads create additional threads by calling Pthread_create.
int pthread_create (pthread_t *tid,pthread_attr_t *attr,func *f,void *arg); Success returns 0, non-zero error
When the function returns, the parameter TID contains the ID of the newly created thread, and the new thread can obtain its own thread ID by calling the Pthread_self function.
pthread_t pthread_self (void); Returns the caller's thread ID.
Terminating a thread
When the thread routine of the when top layer returns, the line terminates Cheng. By calling the Pthread_exit function, the line terminates Cheng
void Pthread_exit (void *thread_return);
Reclaim a terminated thread resource
The thread waits for another thread to terminate by calling the Pthread_join function.
int Pthread_join (pthread_t tid,void **thread_return); Success returns 0, non-zero error
Detach thread
At any point in time, threads are either associative or separable. A binding thread can be recovered by another thread and killed, and its memory resource is not released until it is recycled. The detached thread is the opposite, and the resource is freed automatically when it terminates.
int pthread_deacth (pthread_t tid); Success returns 0, non-zero error
Initializing threads
Pthread_once allows initialization of state related to thread routines.
pthread_once_t once_control=pthread_once_init;int pthread_once (pthread_once_t *once_control,void (*init_routine) ( void)); Always returns 0
12.4 Shared variables in multi-threaded programs
"Thread Memory Model"
Each thread has its own separate thread context, including a unique integer thread ID, stack, stack pointer, program counter, general purpose register, and condition code.
"Mapping variables to storage"
- Global variables: Variables defined outside the function
- Local automatic variable: A variable that is defined inside a function but does not have a static property.
- Local static variable: A variable that is defined inside a function and has a static property.
"Shared Variables"
When and only if one instance of a variable is referenced by more than one thread, the variable is said to be shared.
12.5 Synchronizing Threads with semaphores
"Progress Map"
The execution model of n concurrent threads is modeled as a trace line in an n-dimensional Cartesian space, and the instruction is modeled as a transition from one state to another.
Conversion rules:
- The legitimate conversion is to the right or up, that is, one instruction in a thread is completed
- Two directives cannot be completed at the same time, i.e. diagonal lines are not allowed
- The program cannot run in reverse, i.e. it cannot appear down or to the left
"Signal Volume"
- P (s): if S is nonzero, p will subtract s by one and return immediately. If S is zero, then the thread is suspended until s becomes nonzero.
- V (s): add s plus one, if there is any thread blocking in P operation waiting for s to become nonzero, then the V operation restarts one of the threads, then the thread will subtract s one and finish his P operation.
12.6 using threads to improve parallelism
The speedup ratio of a parallel program is typically defined as:
where P is the number of processor cores, T is the run time on p cores.
12.7 Other concurrency issues "thread safety"
Four disjoint thread unsafe function classes and Countermeasures:
- Functions that do not protect shared variables--protect shared variables with synchronous operations such as P and V
- A function that maintains a state that spans multiple calls--overrides without any static data.
- Returns a function that points to a pointer to a static variable--rewrite; Use lock-copy technology.
- function calling thread unsafe function--refer to the previous three types
Competition
Competition occurs when the correctness of a program relies on one thread to reach the X point of his control flow before another thread reaches the y point.
To eliminate the competition, I can dynamically allocate a separate block for each integer ID and pass it to the thread routine with a pointer to the block.
"Deadlock"
Deadlock: A set of threads is blocked, waiting for a condition that will never be true.
- Programmers use P and V to operate improperly so that the forbidden areas of two semaphores overlap.
- Overlapping forbidden areas cause a set of states called deadlock zones.
- Deadlock is a rather difficult problem because it is unpredictable.
Mutex lock Order rule : If for each pair of mutex (S,T) in the program, assign a whole order to all the locks, each thread requests the lock in this order, and is released according to reverse, the program is deadlock-free.
How to resolve a deadlock
do not let a deadlock occur:
- Static strategy: Design appropriate resource allocation algorithm, do not let deadlock occur---deadlock prevention ;
- Dynamic policy: When a process requests a resource, the system reviews whether it will generate a deadlock, and does not allocate--- deadlock avoidance If a deadlock is generated.
Let the deadlock occur:
The process does not restrict the resource when it is requested, the system periodically or irregularly detects if a deadlock occurs and resolves the deadlock---- deadlock detection and cancellation when detected.
Information Security System 13th Week study summary 20135218 Jing Mengxin