Concurrent Programming: Process + thread + coroutine

Modern computer system by one or more processors, main memory, disks, printers, keyboard, mouse, display, network interfaces, and various other input
complex system consisting of output devices, each programmer can not grasp all the details of the system implementation and optimize the management of these components is an extremely challenging
task. So, we need to install a layer of computer software, is an operating system, user program mission is to provide a simple and clear computer module
type, and manages all of the above equipment.

The definition will have: the operating system is used to coordinate, manage and control the computer hardware and software resources of the system program, which is located between hardware and applications.

(The program is running on the system software has some functions, such as browser, music player, etc.)

The definition of the operating system kernel: the kernel of the operating system is a management and control procedures, is responsible for managing all physical computer resources, including: file system
system, memory management, device management and process management.

process:

Universal programmers corresponding to the strip (or cards) has been loaded into the input unit perforated programs and data, and then start the machine to enter into the computer program and data
memory, and then run through the console switch for starting the program data; been calculated the printer outputs the calculation result; results and remove the tape removed the user (or
the card), before allowing the next user on the machine.

Note Point:
programmer needs to make an appointment on the wall chronograph
that only one program in memory by the CPU calls run (serial)

Advantages and disadvantages:

Advantages: programmer exclusive resources in the entire period of application, real-time debug your program, if a bug can be handled on the spot,
drawback: it is a waste for computer providers (you buy a computer 4000 , 365 more than the year in which you use only one day, definitely save costs,
the best use)

Generation computer problems:

Too many human-computer interaction (input ---> calculate ---> Input Output ---> calculate ---> Input Output ---> calculate ---> Output)

The solution:
to save a bunch of people's input into a large wave input, then the order of the calculation (which is problematic, but the second-generation computing is not resolved) and then save the results as
a big wave output, which is a batch system

Operating system formerly known as:

After collecting about an hour batch job, the cards are read into the tape, then the tape is attached to the machine room and to tape. Then the tape is sent to
the engine room and attached to the tape drive. Subsequently, the operator mounts a special program (which was the predecessor of the modern operating system), which is responsible for a read from the tape first
job (Job, or a set of programs) and run, which is written to the second output on the tape, but does not print. After completion of each job from the operating system automatically
read the next job into a tape and run. When a whole batch operation all over, the operator inputs and outputs to the tape, the tape for the next speaking into a number of input
sector, and outputs the magnetic tape to get offline 1041 on one machine (the host computer is not on-line )print

Advantages: Batch
disadvantages: FIG 1 there are two intermediate villain calculation order is still 2

 

 

 

The two main issues for the second generation computer

SPOOLING developed technologies:
the card is able to quickly get the job room read from the disk card, then any time when a job ends, the operating system will be able to work from a magnetic
read belt, put it vacated the memory area operation, this technology is called an external device while the online operation: SPOOLING this technology also for output. When taken
after using this technology, the machine is not in need IBM1401, nor do you have the tape moved around the (middle two villain unemployed), to strengthen the functions of the operating system

Developed a multi-channel programming to address the issue of the implementation of the order:

On the 7094 machine (running machine), if the current job waiting for tapes or wait for other IO operations suspended, CPU is in idle state until the IO operation
is completed, for CPU-intensive scientific computing, less IO operation, a waste of time is not obvious, for commercial data processing, IO wait to reach 80% to 90%, it will
have to solve a waste of CPU phenomenon.

Solution: The memory is divided into several parts, each part storing a different job, shown in Figure 1-5. When a job waiting for IO complete, another job can
use the CPU, memory sufficient to put the job, the CPU utilization can approach 100%

At this time, the third generation of computer is suitable for large-scale scientific computing and busy business data processing, but, in essence, it still is a batch system.
While solving problems such as the above, but more work must be running at the end of all, to get results from a submission to the result of the operation to retrieve the job often
up to several hours.
Imagine a scenario: A C Jun Jun Jun B three programmers while in the debugger, A king once a wrong comma, you may need half a day to see bear
fruit, because the results of Mr. B Mr. C also out of operation a. Time will be longer. In a nutshell: we keep working together, we went to the data (tape)

Many first generation of computer programmers miss the exclusive, instantly debug your program. In order to meet the programmers can quickly get a response, there has been time-sharing operating system

timesharing system: a plurality of multi-channel technology line terminals +

20 clients simultaneously loaded into memory, thinking, 17, in three runs, cpu on the use of multi-channel memory mode process in the three programs, due to the general clients submit
are short and few instructions lossy duration, indexing computer provides fast interactive services for many users, all users are thought to yourself the meter
computer resources

If there are two programs A and B, A program in execution to the half of the process, the need to read a large amount of input data (I / O operation),
but this time the CPU can wait quietly read data to complete the task A continue, so wasted CPU resources.
A program is not in the process of reading the data, so that the program B to perform, when the program has finished reading the data A, allow
the program to pause B, A and then let the program continue?
Of course, no problem, but there is a keyword: Switch
Since it is a switch, then it comes to the state of preservation, recovery state, coupled with program A and program B required system resources
source (memory, hard disk, keyboard, etc. )are different. Naturally you need to have something to record a program A and program B
, respectively, what resources are needed, how to identify a program A and program B, and so on, so there is a process called abstract

Process Definition:

Once the process is a dynamic program execution on a data set.
Process control block generally consists of three parts of the program, the data set, the process.
We describe the preparation procedures used to accomplish the process which features and how to complete;
data set is a program during execution resources required to be used;
performing external change process wherein the process control block for the recording process, the description of the process, the system you can use it to control and manage the process, it is the system
system perceive the only sign of the presence of the process.

Process give one example:
Imagine a computer scientist Marketer good cooking is to bake a birthday cake for his daughter. He had a birthday cake recipes, kitchen has the required
raw materials: flour, eggs, sugar, vanilla juice. In this analogy, the program is to make a cake recipe (i.e., with the appropriate algorithm described form) computer scientist is the processor (CPU),
and the starting material is a cake of various input data. Process that cooks read recipes, take to the sum of the various raw materials and baked cakes and a series of actions.
Now assume that computer scientists son ran into the room crying, saying that his head was stung by a bee. The computer scientists recorded his
shining recipes where did it (save the current state of the process), and then come up with a first-aid manual, follow the directions in which the processing stings. This is
where we see the processor to switch from one process (to make a cake) to another high-priority process (implementation of medical treatment), each process
has its own procedures (recipes and first aid manual). When the bee stings processed, the computer scientist came back to make a cake from his
that step when it leaves continue to do so.

It appears to reduce the consumption of thread context switching, improve the concurrency of the system, and a breakthrough in the process of doing the same thing only drawback,
Shidao concurrent in-process possible.

Assume that a text program, you need to accept keyboard input, the content displayed on the screen, you also need to save the information to your hard drive. If there is only
one process, will inevitably result in the same time can only do the same thing embarrassing (When you save, you can not pass keyboard typing). If more than
one process, and each process a task, process A task is responsible for receiving keyboard input, process B is responsible for the content displayed on the screen of the
task, process C is responsible for the task to save the contents of the hard disk. Here the process of collaboration between A, B, C involved in the process of communication problems, but
there are things ------- text needs to have a common, non-stop switching loss in performance. If a mechanism to make the
tasks A, B, C share resources, such as context switches required to save and restore the contents of the less, the communication can be reduced at the same time brought
to loss of performance, so much the better. Yes, this mechanism is the thread.

Thread, also known as lightweight processes, it is a basic CPU execution unit is the smallest unit of program execution process, by the thread ID, program
counter, register set and stack together to form. The introduction of the thread reduces the overhead of concurrent execution procedures, improve the operating system of concurrent
performance. Thread does not have its own system resources.

A program has at least one process, a process has at least one thread. (Thread can be understood as a process container)
process has a separate memory unit in the implementation process, and multiple threads of shared memory, thereby greatly enhancing the efficiency of the program .
Threads in the implementation process and the process is different. Each entry has a separate thread running, the order of execution sequence and
exit procedures. But the thread is not able to execute independently, it must exist according to the application, providing multiple execution threads controlled by the application.
Process is a program with a certain separate functions run on one set of data on the activities of the process is the system for resource allocation and transfer
a separate unit degrees.
A thread is a physical process, is the basic unit of CPU scheduling and dispatch, it is smaller than the process of the basic unit can operate independently. threads
themselves basically do not have the system resources, it has only a little in the operation of essential resources (such as a program counter, a set of registers and stack) but
it may belong to a the entire process of sharing resources other thread processes owned by
a thread can be created and destroyed another thread; can execute concurrently across multiple threads in the same process.

No matter how many threads you start, you have a number of cpu, Python will be in the implementation of calm at the same time allowing only one thread to run

threading module built on top of the thread module. lower thread module, the original way to handle and control thread, the thread for threading module by the second package,

It provides a more convenient api to deal with thread.

Direct call:

Threading Import
Import Time

DEF sayHi (NUM): # define the function of each thread to run

Print ( "ON running Number:% S"% NUM)

the time.sleep (. 3)

IF the __name__ == '__main__':

T1 = Threading. thread (target = sayhi, args = (1,)) # generates a thread instance
t2 = threading.Thread (target = sayhi, args = (2,)) # generates another thread instance

t1.start () # start the thread
t2 .start () # start another thread

print (t1.getName ()) # get the thread name
print (t2.getName ())

Inheritance of call

import threading
import time


class MyThread(threading.Thread):
def __init__(self,num):
threading.Thread.__init__(self)
self.num = num

def run (self): # define each thread to run and function

print("running on number:%s" %self.num)

time.sleep(3)

if __name__ == '__main__':

t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()

print("ending......")

join&Daemon方法

import threading
from time import ctime,sleep
import time

def ListenMusic(name):

print ("Begin listening to %s. %s" %(name,ctime()))
sleep(3)
print("end listening %s"%ctime())

def RecordBlog(title):

print ("Begin recording the %s! %s" %(title,ctime()))
sleep(5)
print('end recording %s'%ctime())


threads = []


t1 = threading.Thread(target=ListenMusic,args=('水手',))
t2 = threading.Thread(target=RecordBlog,args=('python线程',))

threads.append(t1)
threads.append(t2)

if __name__ == '__main__':

t in Threads for:
# t.setDaemon (True) # Note: must be set before Start
t.start ()
# t.join ()
# t1.join ()
t1.setDaemon (True)

# t2.join () ######## account that under these three join position?
print ( "all over% s" % ctime ())

join (): Before the child thread finishes running, the parent of the child thread thread will be blocked.

setDaemon(True):

         The thread is declared as a daemon thread must be set before the method is called start (), if you do not set a daemon thread hangs the program will be unlimited. This method is basic and join the opposite.

         When we run the program, the implementation of a main thread, the main thread if they create a child thread, the main thread and the child thread on the two forces were divided, each running, then when the main thread is completed

         When you want to exit, it will test whether the child thread to complete. If the child thread is not completed, the main thread will wait for the child threads to complete before exit. But sometimes we need is just the main thread

         Completed, regardless of whether the child thread to complete, and should be the main thread exits together, then you can use it setDaemon method

# Run (): thread run method is performed automatically after the thread object cpu scheduling
# start (): start thread activity.
# IsAlive (): Returns the thread is active.
# GetName (): Returns the thread name.
# SetName (): Set the thread name.

threading module provides a number of methods:
# threading.currentThread (): Returns the current thread variable.
# Threading.enumerate (): Returns a list of running threads. Refers to the thread starts running, before the end, it does not include a thread before starting and after termination.
# Threading.activeCount (): Returns the number of running threads, and len (threading.enumerate ()) have the same result.

 

Guess you like

Origin www.cnblogs.com/zhang-da/p/11457438.html