当前位置:网站首页>[basic 8] - processes and threads
[basic 8] - processes and threads
2022-07-24 05:09:00 【terrific51】
process (Process) It is a description of a running process of a program in a computer . The finished code , When not running , Become a program ; Running code , The running process is called process .
For the operating system , A task is a process (Process), For example, opening a browser is to start a browser process , Open a notepad and start a notepad process , Opening two notebooks starts two Notepad processes , Open one Word It starts a Word process .
Some processes do more than one thing at a time , such as Word, It can type at the same time 、 Spelling check 、 Printing and so on . Within a process , Do many things at the same time , You need to run multiple “ The subtasks ”, We put these in the process “ The subtasks ” Called thread (Thread).
Because every process has at least one thing to do , therefore , A process has at least one Threads . Of course , image Word This complex process can have multiple threads , Multiple threads can execute at the same time , Multithreading is the same as multiprocessing , It is also the operating system that switches between multiple threads quickly , Let each thread run alternately for a short time , It looks like it's being executed at the same time . Of course , Really multithreading at the same time requires multiple cores CPU It's possible .
Threads are the smallest unit of execution , And the process is made up of at least one thread . How to schedule processes and threads , It's entirely up to the operating system , The program itself can't decide when to execute , How long does it take .
Implement multitasking in one program , You can use multithreading and multiprocessing
Multi process
Multi process creation : Use Process class , Every time this class is instantiated , Just create a process object .
Multi process : During the operation of a program , Multiple processes have been generated
1.n A running program — At least n A process
2.1 Procedures ----- There may be only one process , There may also be multiple processes
# Introduce process class
from multiprocessing import Process
import time
# Mission 1
def run1():
print(" Performed the mission 1!")
time.sleep(5)
# Mission 2
def run2():
print(" Performed the mission 2!")
time.sleep(5)
# Mission 3
def run3():
print(" Performed the mission 3!")
time.sleep(5)
#------------------------ Serial
# run1()
# run2()
# run3()
#------------------------ parallel
# Create process object
p1=Process(target=run1) #(target= Task method to be performed )
p2=Process(target=run2)
p3=Process(target=run3)
if __name__=='__main__':
p1.start()# Start the process , Can only write main in
p2.start()
p3.start()
Start the process , Can only write main in
Performed the mission 1!
Performed the mission 2!
Performed the mission 3!
Multithreading
- Thread is CPU The basic unit of dispatch , It is the specific execution unit in the process ;
- The process contains threads , A process contains at least one thread ;
- If a process contains multiple threads , It's called multithreading .
Implementation of multithreading :
| 1. introduce threading modular | |
|---|---|
| 2. Creating thread objects | |
| 3. Start thread |
import threading
import time
def run(name):
print(" Performed the mission !")
time.sleep(5)
#-- Creating thread objects
t1=threading.Thread(target=run,args=("t1",))
t2=threading.Thread(target=run,args=("t2",))
t3=threading.Thread(target=run,args=("t3",))
# Start thread
t1.start()
t2.start()
t3.start()
# Multi process switching consumes CPU More resources
Performed the mission !
Performed the mission !
Performed the mission !
Main thread and child thread
When the program is executed , The program itself is a thread , Called the main thread
Manually created threads , Called a child thread
The main thread will not wait for the sub thread to finish executing , Will directly execute the following code
import threading
import time
def run(name):
print(" Performed the mission !")
time.sleep(5)
#-- Creating thread objects
t1=threading.Thread(target=run,args=("t1",))
t2=threading.Thread(target=run,args=("t2",))
t3=threading.Thread(target=run,args=("t3",))
# Start thread
t1.start()
t2.start()
t3.start()
t1.join()# You need to wait for the current thread to finish executing , Can continue to execute the main thread
t2.join()
t3.join()
print(" completion of enforcement !")
Performed the mission !
Performed the mission !
Performed the mission !
completion of enforcement !
join Method enables the current thread to continue executing the main thread after it finishes executing
Thread lock
When a thread sets a lock , Only wait until the lock is released , To schedule other threads
import threading
num=100
def run(name):
global num
num-=1
print(" Threads ",name," Yes , at present num The value of is :",num)
for i in range(1,101):
t=threading.Thread(target=run,args=(i,))
t.start()
If thread lock is not used , The running results may be disordered
Threads 1 Yes , at present num The value of is : 99
Threads 2 Yes , at present num The value of is : 98
Threads 3 Yes , at present num The value of is : 97
Threads 4 Yes , at present num The value of is : Threads 5 Yes , at present num The value of is :96
95
Threads 6 Yes , at present num The value of is : 94
········
Threads 100 Yes , at present num The value of is : 0
- Use thread lock
import threading
# Thread lock ( The mutex ): When a thread sets a lock , Only wait until the lock is released , To schedule other threads
lock=threading.Lock()# Create a lock
num=100
def run(name):
global num
num-=1
print(" Threads ",name," Yes , at present num The value of is :",num)
for i in range(1,101):
t=threading.Thread(target=run,args=(i,))
t.start()
There will be no confusion
Case study
Multithreaded chat room
from threading import Thread
from socket import *
# Receiving information
def recvData():
msg=s.recv(1024)
print(">>:",msg.decode())
# Send a message
def sendData():
info=input("<<:")
s.sendto(info.encode(),(ip,port))
#--------------------
ip="localhost"# other party ip
port=9001# Opposite port number
s=socket(AF_INET,SOCK_DGRAM)
s.bind(("localhost",9002))
tr=Thread(target=recvData)
ts=Thread(target=recvData)
tr.start()
ts.start()
边栏推荐
- pso和mfpso
- How to register and apply for free for Apple Developer account in order to enjoy the upgrade experience at the first time
- Icml2022 | rock: causal reasoning principle on common sense causality
- yum 查看某个命令由哪个安装包提供
- How to solve the engine prompt alias herodb and game engine startup exceptions?
- 7. Find the sum of numbers between 100 and 300 that can be divided by 3.
- FRP intranet penetration service usage
- 熊市抄底指南
- To 3mm; Provide safe and stable product execution according to the sender IID
- Image to image translation with conditional advantageous networks paper notes
猜你喜欢

几种常见的排序

Event extraction and documentation (2019)

frp内网穿透服务使用

Wang Qing, director of cloud infrastructure software research and development of Intel (China): Intel's technology development and prospects in cloud native

Event extraction and documentation (2020-2021)

PostgreSQL: run PostgreSQL + pgadmin 4 in docker

明星逆市入局的NFT,如何能走出独立行情?

In his early 30s, he became a doctoral director of Fudan University. Chen Siming: I want to write both codes and poems

Middle aged crisis, workplace dad who dare not leave, how to face life's hesitation

Sort - quicksort
随机推荐
Chiitoitsu(期望dp)
The difference between statement and Preparedstatement and how to use placeholders
Kingbase V8R6集群安装部署案例---脚本在线一键扩容
Jiang Xingqun, senior vice president of BOE: aiot technology enables enterprise IOT transformation
How to set up an internal wiki for your enterprise?
Learning pyramid context encoder network for high quality image painting paper notes
NLP learning roadmap (mind map) is very comprehensive and clear!
Print leap years between 1000 and 2000
How can I open and view the bin file? Diagram of reading method of bin file backed up by router
Sort - quicksort
In his early 30s, he became a doctoral director of Fudan University. Chen Siming: I want to write both codes and poems
Foreign key operation of MySQL_ Cascade operation
[machine learning] - [traditional classification problem] - naive Bayesian classification + logistic regression classification
Learning pyramid context encoder network for high quality image painting paper notes
How to register and apply for free for Apple Developer account in order to enjoy the upgrade experience at the first time
Transpose of array sparse matrix
Smart pointer, lvalue reference, lvalue reference, lambda expression
Hanoi problem
Drools development decision table
The second chapter is encog's data acquisition