python-processes, Threads

Source: Internet
Author: User

First, explain:

I believe that all the students will use the operating system, don't say no, don't use the words of my blog, and our operating system you can look at my blog, and listen to music again, speaking of music to everyone recommended a "Shapeof You", And I just listen to the music while writing blog, haha ... So here we are going to think about how our computers are calculated? How do you start so many tasks at the same time? And there are a lot of tasks secretly running in the background, but there is no display on the desktop.

And now multi-core multithreaded computer has been very popular, yes, so the calculation of concurrency can be more faster, but when the computer was just popular, many single-core CPUs and how to perform multi-tasking it? After all, the CPU execution code is executed sequentially, and the answer is that the operating system on the computer turns the tasks to perform alternately, Task a executes for 0.01 seconds, switches to task B for 0.01 seconds, then switches to task 3, so it repeats itself, and on the surface, each task is executed alternately, but because the CPU is executing too fast, we feel as if all the tasks are executing at the same time.

So, in our daily running environment, multitasking can only be done on multi-core multithreaded CPUs, but we sometimes have more tasks than the cores of CPUs, so the operating system automatically shifts many tasks to each core execution.

For the operating system, a task is a process, such as open a browser is to start a browser process, open a notepad started a Notepad process, open two Notepad started the two Notepad process, open a word started a word process.

Some processes do more than one thing at the same time, such as word, which can be typed, spell-checked, and printed at the same time. Within a process, to do multiple tasks at the same time, you need to run multiple "subtasks" at the same time, and we refer to these "subtasks" in the process as threads (thread).
Because each process has at least one thing to do, a process has at least a single thread. Of course, a complex process such as word can have multiple threads, multiple threads can execute simultaneously, multithreading is performed the same way as multiple processes, and the operating system quickly switches between multiple threads, allowing each thread to run briefly alternately, seemingly as if it were executing concurrently. Of course, a multi-core CPU is required to actually execute multiple threads at the same time.

Summarize:

Application---> Process---> Threads

The application has at least one process, and a process finally has a main thread, and a program can start more than one process, a process can launch multiple threads, and they all have their own main process and the main thread, and the process and threads are CPU to calculate the way is to switch operations back and forth.

Threads and processes python differs from other development languages in that other language threads can switch between multiple CPUs, while Python does not support multi-threading, only multiple processes (provided the CPU is called), so the following scenarios occur

Application Scenarios:

IO-intensive: Multithreading

COMPUTE-Intensive: multi-process

GIL, Global interpreter lock, ensures that only one thread in the same process is called at the same time

Second, the use of the thread

Look at the code

ImportThreading#module for importing ThreadsImport TimedefTask (a):#functions of the processTime.sleep (1)#Wait a second    Print(a) forIinchRange (30): #同时启动30个线程 t= Threading. Thread (Target=task,args=[i,])#The process is created and target represents the process to be createdT.start ()#process Start, indicating start of workPrint("End")#start the main process

The use of Setdaemon

Description: Setdaemon Sets whether the main process waits for the child thread to end, and then ends itself with the default option (False)

Example: (default option)

ImportThreading#module for importing ThreadsImport TimedefTask (a):#functions of the processTime.sleep (1)#Wait a second    Print(a) forIinchRange (5): T= Threading. Thread (Target=task,args=[i,])#The process is created and target represents the process to be createdT.setdaemon (False)#whether the main process waits for a child thread, False is to wait for true to not waitT.start ()#Process StartPrint("End")#start the main process## #输出如下:C:\Python35\python.exe d:/linux/python/day-test/day9/test1.pyend02134

Non-default option (True)

Import Threading    #导入线程的模块
Import time
Def task (a): #进程的函数
Time.sleep (1) #等待一秒
Print (a)
For I in range (5):
t = Threading. Thread (Target=task,args=[i,]) #创建了进程, Target represents the process to be created
T.setdaemon (True) #主进程是否等待子线程, False is to wait for True to not wait
T.start () #进程启动
Print ("End") #启动主进程

The output is as follows:
ImportThreading#module for importing ThreadsImport TimedefTask (a):#functions of the processTime.sleep (1)#Wait a second    Print(a) forIinchRange (5): T= Threading. Thread (Target=task,args=[i,])#The process is created and target represents the process to be createdT.setdaemon (True)#whether the main process waits for a child thread, False is to wait for true to not waitT.start ()#Process StartPrint("End")#start the main process##下面没有等子线程就结束C:\Python35\python.exe d:/linux/python/day-test/day9/Test1.pyendprocess finished with exit code 0

Join usage

ImportThreading#module for importing ThreadsImport TimedefTask (a):#functions of the processTime.sleep (3)#Wait a second    Print(a) forIinchRange (5): T= Threading. Thread (Target=task,args=[i,])#The process is created and target represents the process to be createdT.setdaemon (False)#whether the main process waits for a child thread, False is to wait for true to not waitT.start ()#Process StartT.join ()#等待的最大时间, waiting for the child thread to run, default to always waitPrint("End")#start the main process#Output:C:\Python35\python.exe d:/linux/python/day-test/day9/test1.py01234End


Lock on thread

Single lock

ImportThreadingImportTimev= 10#1, only one person can use the lock#lock = Threading. Lock () #此锁只能锁一次Lock = Threading. Rlock ()#This lock can lock multiple layersdefTask (ARG): Time.sleep (2)    #apply lock, other people waitLock.acquire () Lock.acquire () Lock.acquire ( )Globalv v-= 1Print(v)#Releaselock.release () lock.release () lock.release ( ) forIinchRange (10): T= Threading. Thread (target=task,args=(i,)) T.start ()

Multi-person Lock

ImportThreadingImportTimev= 10#1, more people use the lockLock= Threading. Boundedsemaphore (3)#This lock can be used by multiple people using 3 for 3 persons simultaneouslydefTask (ARG):#Time.sleep (2)    #apply lock, other people waitLock.acquire () time.sleep (1)    Globalv v-= 1Print(v)#Releaselock.release () forIinchRange (10): T= Threading. Thread (target=task,args=(i,)) T.start ()

Event Lock

ImportRequestsImportThreadingImportTimelock= Threading. Event ()#How the Process locksdefTask (ARG): Time.sleep (1) lock.wait ()#process waiting for command, unlocking    Print(ARG) forIinchRange (5): T= Threading. Thread (target=task,args=(i,)) T.start () whileTrue:value= Input (">>>>>")    ifValue = ="1": Lock.set ()#Unlock#Output:C:\Python35\python.exe d:/linux/python/day-test/day9/event lock. PY>>>>>>>>>>2>>>>>1 #输入1之后开锁 >>>>>04312

Custom lock, set the number of locks on the thread yourself

ImportThreadingImportTimelock=Threading. Condition ()defTask (ARG): Time.sleep (1)    #Lock All ThreadsLock.acquire ()#Get lockLock.wait ()#Lock Waiting    #apply lock, other people wait    Print("Threads", Arg) lock.release ()#Release Lock forIinchRange (10): T= Threading. Thread (target=task,args=(i,)) T.start () whileTrue:value= Input (">>>>>>>>") Lock.acquire ()#Get locklock.notify (int (value))#set the freed thread, you write several of the above threads to release severalLock.release ()#Release Lock

Output:

>>>>>>>>6>>>>>>>> Threads 24318

python-processes, Threads

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.