Python basics (multitasking, parallel and concurrency, synchronization and asynchrony, process and thread, multithread implementation)

Multitasking

Multitasking: perform multiple tasks at the same time period/at the same time
The purpose of multitasking is to improve efficiency

Parallel and concurrency

Parallel refers to the execution of multiple tasks at the same time, and multiple tasks are executed together.
Concurrency refers to the execution of multiple tasks within a period of time, but the tasks are not executed at the same time, but executed in turn

Synchronous and asynchronous

Synchronization means that two tasks are related. The latter may require the result of the former. The serial execution is
asynchronous but means that the two tasks are not connected, can be executed simultaneously, or executed one by one (without distinction). Concurrent

Process and thread

A process is a warehouse of threads.
A process may contain multiple threads

进程
	一个正在运行的程序就是一个进程,进程是系统进行资源分配的最小单位
	每一个进程都有自己的独立的内存和资源
	程序只有一个,进程可以有多个
	进程与进程之间相互独立,资源不能共享
线程
	线程是进程中的一个执行线路或者流程
	线程是任务调度的最小单位
	线程可以看做是轻量级的进程
	程序真正执行时,调用的是线程
	一个进程中至少有一个主线程,可以包含多个子线程
	线程与线程之间共享进程的资源和数据

Multi-threaded realization

Use the threading module to create threads

import threading
def sing(nmaes):
	print(f"第一个线程{names}")
if __name__ == '  main  ':
	# 创建一个线程,args后面写要传的参数,必须是元组的形式
	t1 = threading.Thread(target=sing, args=("老王",))
	# 启动线程
	t1.start()

Class inheritance method to create a process

import threading
class MyThrea(threading.Thread):
	def __init__(self, username):
		super().__init__()
		self.username = username
	
	# run方法重写父类中的run方法 
	# 在实例化完后,进程开始会自动调用run方法
	def run(self):
		print(f"{self.username}唱了歌")
if __name__ == '  main  ':
	t1 = MyThrea('老王')
	t2 = MyThrea('老李')

	# 设置线程的名字
	t1.setName("t1")
	# 获取线程的名字
	print(t1.getName())

	# 启动进程
	t1.start()

Guess you like

Origin blog.csdn.net/weixin_44781625/article/details/108540144