程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python learning - basic thread learning

編輯:Python

Python Study --- Basic thread learning


Thread basis

What is thread (thread)

Thread is ​CPU​ Scheduling is the smallest unit that can perform operational scheduling . It is included in the process , Is the actual operation unit in the process . A thread refers to a single sequential control flow in a process ​[ In other words , A thread is a collection of instructions ]​, Multiple threads can be concurrent in one process , Each thread performs different tasks in parallel

Thread execution characteristics


Thread only 3 A basic state : be ready , perform , Blocking .

Threads exist 5 There are three basic operations to switch the state of a thread : The derived , Blocking , Activate , Dispatch , end .


What is a process (Process)
​ process , Is the concurrent execution of a program during execution ​ operating system ​ The basic unit for allocating and managing resources , It's a dynamic concept , Competing for the basic unit of computer system resources . Each process has its own address space , That is, process space or ( Virtual space ). The size of the process space It's only about the number of bits in the processor

Process development subprocess , Child process complete Copy The parent process , For example, the parent process occupies 20M, Subprocesses also occupy 20M, So starting a process consumes more resources than starting a thread

The difference between thread and process


The thread shares the address space of the process that created it ; The process has its own address space .

Threads can directly access the data segments of their processes ; A process has its own copy of the data segment of its parent process .

A thread can communicate directly with other threads of its process ; Processes must use interprocess communication to communicate with sibling processes .

New threads are easy to create ; The new thread needs to repeat the parent thread .​ For example, the parent process occupies 20M, Subprocesses also occupy 20M, So starting a process consumes more resources than starting a thread

Threads can interoperate with each other , Between processes cannot

Changes to the main thread ( Cancel , Priority change, etc ) Other child threads of the process may be affected ; Changes to the parent process do not affect the child process .


ask : Is the thread executing faster or the process executing faster ?[ Trap question ]

answer : As fast as , The content of running is the same

Python You can create multiple processes , Not strictly speaking, because there are GIL,Python No multithreading , But you can use multiple processes to solve [ Data sharing cannot be realized under multiple processes , It can be solved by others , coroutines , Heap, etc ] Realization CPU The use of multicore

If in py Inside , The task is IO intensive [ Not always call CPU Perform tasks , There will be sleep etc. IO Blocking ], Multithreading , If it's computationally intensive , You can consider C Development

Thread creation

Thread creation :


1. Call directly ,threading.Thread(target=sayhi,args=(1,)

2. Call by inheritance :


Call directly :

import time

import threading
begin=time.time()
def bar(n):
print('bar%s'%n)
time.sleep(3)
def foo(n):
print('foo%s' %n)
time.sleep(2)

t1 = threading.Thread(target=bar, args=(1,)) # establish t1 Thread object
t2 = threading.Thread(target=foo, args=(2,)) # establish t2 Thread object
t1.start() # Thread start , Start grabbing CPU resources
t2.start() # Thread start , Start grabbing CPU resources
end=time.time()
t1.join() # Thread blocking , Days after execution t1 Execute the main thread after
t2.join() # Thread blocking , Days after execution t2 Execute the main thread after
end2 = time.time()
print(' At this time there is 3 Threads , The main thread ,t1 Threads , t2 Threads ')
print(end-begin)
print(end2-begin)
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

​​

Call by inheritance :

import threading

import time
class MyThread(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num
def run(self): # Defines the function to run for each thread
print("running on number:%s" % self.num)
time.sleep(3)
if __name__ == '__main__':
t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

Thread common methods

Thread.join():​ Before the child thread finishes running , The parent of this child thread will always be blocked .

import threading

from time import ctime,sleep
import time

def music(func):
for i in range(2):
print ("Begin listening to %s. %s" %(func,ctime()))
sleep(4)
print("end listening %s"%ctime())

def move(func):
for i in range(2):
print ("Begin watching at the %s! %s" %(func,ctime()))
sleep(5)
print('end watching %s'%ctime())

threads = []
t1 = threading.Thread(target=music,args=(' Qi li xiang ',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(' Forrest gump ',))
threads.append(t2)

if __name__ == '__main__':

for t in threads:
t.start() # t1.start(). t2.start()
# t.join() # Serial execution ,t1.start() after , Get into t1.join() wait until t1 After the execution is finished t2
# t.join() # Python The last one is selected by default for Cyclic t2, Equivalent to t2.join()
# t1.join() # Main thread print() It will be in the 8 Second out , Finally print end movies
t.join() # t2.join(),t2 perform end After the end of the program
print ("all over %s" %ctime())
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.

setDemaon(True):

Declares a thread as a daemon thread , Must be in start() Set before method invocation , If not set to daemon thread the program will be suspended indefinitely . This method is the basic sum join It's the opposite . When we're running the program , Execute a main thread , If the main thread creates another child thread , Main thread and child thread Just split up , Run respectively , So when the main thread finishes and wants to exit , The child thread is checked for completion . If the child thread does not complete , The main thread waits for the child thread to complete before exiting . But sometimes what we need is As long as the main thread is finished , Does not pipe whether the thread is finished , Exit with the main thread , That's when you can use setDaemon(True)

import threading

from time import ctime,sleep
import time

def music(func):
for i in range(2):
print ("Begin listening to %s. %s" %(func,ctime()))
sleep(4)
print("end listening %s"%ctime())

def move(func):
for i in range(2):
print ("Begin watching at the %s! %s" %(func,ctime()))
sleep(5)
print('end watching %s'%ctime())

threads = []
t1 = threading.Thread(target=music,args=(' Qi li xiang ',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(' Forrest gump ',))
threads.append(t2)

if __name__ == '__main__':
# t2.setDaemon(True) # perform t1 And then we'll finish the program , That is to say, no execution print('end watching %s'%ctime())
for t in threads:
t.setDaemon(True) # Declares a thread as a daemon thread , Must be in start() Set before method invocation
t.start() # t1.start(). t2.start()
print ("all over %s" %ctime())
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.

​​

Thread Methods for providing threads

thread Other methods provided by the module :

threading.currentThread(): Returns the current thread variable .
threading.enumerate(): Returns a thread containing the running thread list. Running after the thread starts 、 Before the end of the , Threads before and after startup are not included .
threading.activeCount(): Returns the number of running threads , And len(threading.enumerate()) It has the same result .
In addition to the method of use , The thread module also provides Thread Class to handle threads ,Thread Class provides the following methods :
run(): The method used to represent thread activity .
start(): Start thread activity .
join([time]): Wait until thread aborts . This blocks the calling thread up to the thread's join() Method called to abort - Exit normally or throw unhandled exception - Or optional timeout occurs .
isAlive(): Returns whether the thread is active .
getName(): Return thread name .
setName(): Set the thread name .
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.

python Of GIL(Global Interpreter Lock)

Interpreter reason : because Cpython Explain why , The interpreter can only call one thread at a time , You can understand Python No multithreading

CPython Implementation details : stay CPython in , Because the global interpreter is locked , Only one thread can execute at a time Python Code ( Even some performance oriented libraries may overcome this limitation ). If you want your application to make better use of the computing resources of multi-core computers , It is recommended that you use multiprocessing . however , If you want to run multiple I / O For intensive tasks , Threads are still a suitable model .



author :​​ Small a ninety-seven ​​​ ​

-------------------------------------------

Individuality signature : Everything is good in the end , If it's not good , That means things haven't come to the end yet ~

The copyright of this article belongs to the author 【​​ Small a ninety-seven ​​​】, Welcome to reprint , However, this statement must be retained without the consent of the author , And in the article page obvious position gives the original link , Otherwise, the right to pursue legal responsibility is reserved !




  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved