Process & Thread-related knowledge

Source: Internet
Author: User
Tags message queue mutex semaphore terminates

Regardless of java,c++, there are process, thread-related content. Let's tidy up here.

The python thread, in fact, is a pseudo-thread and cannot be really concurrent. There is also a talk below.

The thread itself basically does not own the system resources, only has a point in the operation of the necessary resources (such as program counters , a set of registers and stacks ).

Multiple threads share memory.

Reference this article: http://www.cnblogs.com/qiaoconglovelife/p/5319779.html

    • Process and PCB

     Process: A process is a process of execution of a program, is a system of resource allocation and scheduling of an independent unit.

    process Entity (process image): Consists of the program segment, the related data segment and the PCB three parts. The process is dynamic and the process entity is static.

    PCB (Process Control block): The system uses the PCB to describe the basic situation and running state of the process, and then control and manage the process; so-called create process, is actually the creation process image of PCB;PCB is the only sign that the process exists.

There are 5 states of the process, the first 3 of which are the basic states:

Operation state, ready state, blocking state (waiting state). The other two types are the new state and the terminating state.

    • Process creation Process

(1) Assign ID and PCB: Assign a unique process identification number to the new process and request a blank PCB (PCB is limited). If the PCB application fails, the creation fails.

(2) Allocating resources: Allocate the necessary memory space (embodied in the PCB) for the program and data of the new process, as well as the user stack . Note: If there are insufficient resources (such as memory space), this is not a failed creation, but is in a blocking state.

(3) Initialize the PCB: The main initialization (1) flag information (2) Processor status information (3) processor control information, and (4) Set the priority of the process and so on.

(4) Scheduling: If the process-ready queue is able to accommodate the new process, the new process is inserted into the ready queue, waiting to be scheduled to run.

Note that the creation of a process is an atomic operation that is not allowed to break during execution and is an indivisible basic unit.

    • Termination of the process

The main events that cause the process to terminate are:

(1) Normal end

(2) Abnormal end: such as storage area out of bounds, illegal instructions, I/O failure, etc.

(3) External intervention: such as operator or operating system intervention, parent process request, parent process termination.

The process by which the operating system terminates the process is as follows:

(1) based on the ID of the terminated process, retrieve the PCB and read out the status of the process.

(2) If the terminated process is in the execution state, immediately terminates execution of the process and allocates processor resources to other processes

(3) If the process has child processes, all of its child processes should be terminated

(4) The resources owned by the process are either returned to their parent process or returned to the operating system

(5) Remove the PCB from the queue in which it is located (linked list).

    • Switching between processes

(1) Save processor context , including program counters and other registers .

(2) Update the PCB information .

(3) The PCB of the process is moved into the corresponding queue, such as ready, in an event blocking queue.

(4) Select another process to execute and update its PCB.

(5) Update the data structure of memory management.

(6) Restore the processing machine context.

Note: The difference between "dispatch" and "toggle": Scheduling refers to the behavior that determines which process the resource is assigned to, and is a decision-making behavior; switching refers to the actual assigned behavior, which is the execution behavior. In general, there is the scheduling of resources, and then the process of switching.

    • Thread

A thread is a lightweight process that is the smallest unit of a program's execution flow, consisting of a thread ID, a program counter , a collection of registers , and a stack ; the thread itself does not own system resources and only has a few resources that are essential in the run. However, it can share all of the resources owned by the process with other threads that belong to one process.

    • Process and Thread differences

(1) A program has at least one process, and a process has at least one thread. A thread is an entity of a process that is the basic unit of CPU dispatch and dispatch;

(2) The process has a separate memory unit, while multiple threads share memory. Thus the thread efficiency is higher;

(3) The process has a separate address space, after a process crashes, in the protection mode will not affect other processes, and the thread does not have a separate address space, a thread dead is equal to the entire process dead, so the multi-process program is more robust than multithreaded programs;

(4) The process of switching, the cost of large resources, the efficiency is poor;

(5) process is the basic unit of system resource allocation, and thread is the basic unit of dispatch.

Thread-Exclusive content: thread context, includingThread ID、Stack、stack Pointer、PC (program counter), General purposeRegister Device, condition code. What the thread shares: file descriptors and the entire user virtual address space, including read-only text (code), static variables, heaps, all shared library code, and data regions.

    • What are the benefits of threading compared to a process

(1) Easy to dispatch.

(2) Improve concurrency. Concurrency can be easily and efficiently achieved through threading. A process can create multiple threads to perform different parts of the same program.

(3) less overhead. Creating a line turndown creates a process that is fast and requires little overhead.

(4) Facilitate the full use of multi-processor functions.

    • What are the disadvantages of a thread compared to a process

(1) synchronization between threads and lock-in control is more troublesome

(2) The crash of a thread affects the stability of the entire program

(3) After the thread is too much, the scheduling of the thread itself is also a hassle, requiring more CPU consumption

    • Detach thread
      • Threads can be either associative or separable;
      • A thread can be combined to recover its resources and kill by other threads . Before being reclaimed by another thread, its memory resources (such as stacks) are not released , whereas a separate thread cannot be recycled or killed by other threads. Its memory resource is automatically released by the system when it terminates ;
      • To avoid memory leaks, each of the bonded threads should be explicitly retracted by other threads, or separated by calling the Pthread_detach function (which corresponds to Java is thread.join and Thread.detach)
      • By default, threads are created to be combined . (Note: A binding is a state that calls the Join method to bind/release)

Here's an example:

 PackageCom.company;Import StaticJava.lang.Thread.sleep;classSolution {}classMyrunnableImplementsRunnable {intx = 5; @Override Public voidrun () {synchronized( This) {             for(inti = 0; I < 5; i++) {System.out.println ("HI" + thread.currentthread (). GetName () + ":" + x--); }} System.out.println ("Here to Sleep"); Try{sleep (5000); } Catch(interruptedexception e) {e.printstacktrace (); }    }} Public classMain { Public Static voidMain (string[] args)throwsinterruptedexception {myrunnable Mr=Newmyrunnable (); Thread T1=NewThread (MR, "1"); Thread T2=NewThread (MR, "2"); Thread T3=NewThread (MR, "3");        T1.start ();        T2.start (); T3.start ();System.out.println (); }}

Printing results:

Hi 1:51:41:31:21:13:03:-13:-23:-3  3:-42:-52:-62:-72:-82:-9 here tosleep

Three threads, and sleep for 5 seconds before the entire program ends.

If synchronized is added to the function, then each thread is sleep for 5 seconds and sleep for 15 seconds.

    • IPC Mode (inter-process communication mode)

(1) Pipe: Half-duplex, used between father and son, brother.

(2) Named pipes (FIFO)

(2) Message Queuing: The message chain list is stored in the kernel, each message queue is identified by a message queue identifier; Unlike a pipeline, Message Queuing is stored in the kernel and only one message queue can be deleted when the kernel is restarted, and the size of the message queue is restricted.

(3) Semaphore (Semophore): Commonly used to deal with critical resource access synchronization problems. Critical resource: A resource that can be manipulated by only one process or thread at a time.

(4) Shared memory: Can be said to be the most useful inter-process communication mode , but also the fastest IPC form .

(5) Socket: can also be used between different machines.

(6) signal (Signal)

    • Thread synchronization Mode

(1) Critical section: When multiple threads access an exclusive shared resource, a critical section object can be used. A thread with a critical section can access a protected resource or snippet, and other threads will be suspended until the thread that owns the critical section discards the critical section if they want to access it.

(Note: Java's synchronized code snippet, also barely can be counted as the critical section, is only the implementation of the language tag mutex; To access the code snippet, you need to get the lock on the object that is passed to synchronized. Note that each Java object has a lock hidden .

Java GC requires safe point, in order for multiple threads to stop, the marked area-other threads do not come in, the inside of the thread comes out, the beginning gc-with the critical section of the idea also a little bit like

(2) Mutex-mutex: A mutex object is very similar to a critical section object, except that it is allowed to be used between processes, while a critical section restricts use only between threads of the same process .

(3) Condition variable: A thread is suspended until an event occurs.

(4) Semaphore: A semaphore object can be used when a counter is required to limit the number of threads that can use a shared resource. The CSemaphore class object holds the count value of the thread that currently accesses a specified resource, which is the number of threads that can currently use the resource. If the count reaches 0, all access attempts to the resources controlled by the CSemaphore class object are placed in a queue until the timeout or count value is not zero.

(5) Event: Allows a thread to actively wake up another thread to perform a task after it has finished processing a task.

(6) Socket

Feel this article is good, there is a certain depth. You can read more about this blog: http://www.cnblogs.com/qiaoconglovelife/

Let's talk a little bit about Python threads.

In short, as probably the only multi-threaded interpreted language (Perl multithreading is disabled, PHP is not multi-threading), Python multithreading is compromise, at any time only a Python interpreter in the interpretation of Python bytecode. Ruby also has thread support, and at least Ruby MRI has a Gil.

A separate article to write, detailed content can read this article: http://www.cnblogs.com/charlesblc/p/6135819.html


Process & Thread-related knowledge

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.