Python基础(二)进程线程协程

Python基础进程/线程/协程(二)

魔术方法
#__doc__ 类的描述信息
#__module__ 当前操作的对象在哪个模块
#__class__ 当前操作的对象的类
#__init__  类创建对象的时候自动执行
#__del__   对象被释放的时候调用
#__call__   对象被释放的时候调用
#__str__   打印对象的时候调用
#__dict__  获取对象信息 返回字典
#__getitem__ 索引获取操作
#__setitem__ 设置获取操作
#__delitem__ 删除获取操作

class Student():
   """类的描述信息"""
   def add(self):
       """方法的描述信息"""
   def __init__(self):
       print("init")
   def __del__(self):
       print("del")
   def __call__(self, *args, **kwargs):
       print("call")
   def __str__(self):
       print("str")
   def __getitem__(self,key):
       print("__getitem__")
   def __setitem__(self,key,value):
       print("__setitem__")
   def __delitem__(self,key):
       print("__delitem__")
student=Student()
print(Student.__doc__)
print(Student.__module__)
print(Student.__class__)
del student#删除对象
student()#调用call
print(Student)#调用str
print(student.__dict__)#实例对象的字典
print(Student.__dict__)#Object的字典
print(student['a'])#__getitem__
student['a']=10#__setitem__
del student['a'#__delitem__
python发送邮件
#pip install yagmail
import yagmail
yag = yagmail.SMTP(user="1141522068@qq.com",password="dpfcycfpnodzhgcc",host="smtp.qq.com",port=465)
content="python email test"
yag.send("1141522068@qq.com","subject",content)
网络问题
#三次握手: 1.client->server:hello    2.server->client:收到你的hello了   3.client->server:收到你的回复了
#四次挥手:(关闭连接)  1.client->server:关闭  2.server->client:同意关闭请求,开始关闭处理资源

#   3.server->client:同意关闭请求,我的资源已经清理完成  4.client->server:关闭 在等待2MSL再关闭(30s-2min)
#链路层->网络层(IP)->传输层(TCP,UDP)->应用(HTTP,SFTP)

#长连接:Connection:Keep-alive    短链接:每次传输都建立连接
多线程锁
import time
import threading
g_num=0   ###全局变量
def sing():
   global g_num
   for i in range(5000000):
       #lock1.acquire() ##上锁
       g_num+=1
       #lock1.release() ##开锁
   print(g_num)
#thread_list = threading.enumerate()
#print("线程数量",len(thread_list))
#thread_pool = threading.Thread(target=sing,daemon=True) ##父进程结束后自己页结束
thread_pool = threading.Thread(target=sing)  ##函数必须是只写方法名
thread_pool1 = threading.Thread(target=sing) ##函数必须是只写方法名
lock1 = threading.Lock()
#thread_list = threading.enumerate()
#print("线程数量",len(thread_list))
thread_pool.start()
#thread_pool.join()  ##该线程执行完成后,其他的才能执行 影响性能
thread_pool1.start()
#thread_pool1.join()
自定义线程类
import time
import threading
class MyThread(threading.Thread):
   def __init__(self,num):
       super().__init__()
       self.num=num+10
   def run(self):
       for i in range(5):
           print("sing",self.name,self.num)
           time.sleep(1)
if __name__ == '__main__':
   thread = MyThread(10)
   thread.start()
   thread1 = MyThread(15)
   thread1.start()
   print("main")
进程
import multiprocessing
from multiprocessing import Process
import time

def sing():
   for i in range(5):
       time.sleep(0.5)
   print("sing",multiprocessing.current_process().pid)
   print("sing",multiprocessing.parent_process().pid)
if __name__ == '__main__':
   process = Process(target=sing)#进程执行的时候是复制了一份。线程是共享的
   #CPU密集进程优先选择  IO密集线程优先选择
   process.start()
   print(process.name,process.pid,process)
队列
import multiprocessing
from multiprocessing import Process
import time
queue = multiprocessing.Queue(5) ##初始化长度未5的队列.每个元素可以不一样
queue.put("4")
queue.put([1,2,3])
print(queue.full(),queue.empty())##是否满了  是否空
print(queue.qsize(),queue.get(),queue.get())##只能按照顺序取
进程之间依靠队列通信
import multiprocessing
from multiprocessing import Process
import time
def write(queue):
   for i in range(5):
       queue.put(i)
       print("write",i)
       time.sleep(5)
def read(queue):
   for i in range(5):
       print("read",queue.get())##阻塞式读取
if __name__ == '__main__':
   queue = multiprocessing.Queue(5)
   process_write = Process(target=write,args=(queue,))##方式有点奇怪
   process_read = Process(target=read,args=(queue,))##方式有点奇怪
   process_write.start()
   process_read.start()
进程池
import multiprocessing
import time
def write():
   for i in range(5):
       print(multiprocessing.current_process().pid)
       time.sleep(1)
#apply一个进程执行完成后,才执行下一个。
#apply_async 可以同时执行进程
if __name__ == '__main__':
   pool = multiprocessing.Pool(3)##进程池
   for i in range(5):
       pool.apply_async(func=write)
   pool.close()##不接受新任务 等待结束
   pool.join()##主进程等待进程池执行结束,再退出
进程池之间的通信
import multiprocessing
import time
def write(queue):
   for i in range(5):
       queue.put(i)
       print("write",i)
       time.sleep(5)
def read(queue):
   for i in range(5):
       print("read",queue.get())##阻塞式读取
#apply一个进程执行完成后,才执行下一个。
#apply_async 可以同时执行进程
if __name__ == '__main__':
   pool = multiprocessing.Pool(4)##进程池
   queue = multiprocessing.Manager().Queue(4)##进程池
   pool.apply_async(func=write,args=(queue,))
   pool.apply_async(func=read,args=(queue,))

   pool.close()##不接受新任务 等待结束
   pool.join()##主进程等待进程池执行结束,再退出
进程池拷贝文件
#文件放大有用,文件小反而慢了
import multiprocessing
import os
import datetime
source_path = "D:\data\\aa\\"
target_path = "D:\data\\bb\\"
def copyFile(index):
   print(multiprocessing.current_process().pid)
   sorce = open(source_path+index,"rb")
   target = open(target_path+index,"wb")
   target.write(sorce.read())
   sorce.close();
   target.close();
if __name__ == '__main__':
   list = os.listdir(source_path)
   pool = multiprocessing.Pool(2)##进程池
   print(datetime.datetime.now())
   for index in list:
       pool.apply_async(copyFile, args=(index,))
       #copyFile(index)
   pool.close()##不接受新任务 等待结束
   pool.join()##主进程等待进程池执行结束,再退出
   print(datetime.datetime.now())
协程
#协程一秒钟切换上百万次都是可以的 yield必须显示调用next
import time
def work1():
   print("work")
   while(True):
       print("work1 start")
       yield
       time.sleep(1)
       print("work1 end")
def work2():
   while(True):
       print("work2 start")
       yield
       time.sleep(0.5)
       print("work2 end")
if __name__ == '__main__':
   w1=work1()
   w2=work2()
   while(True):
       next(w1)
       next(w2)
greenlet
#自行调度的协程(上面代码太麻烦) pip install greenlet
from greenlet import greenlet
import time
def work1():
   while(True):
       print("work1 start")
       time.sleep(1)
       w2.switch()
def work2():
   while(True):
       print("work2 start")
       time.sleep(1)
       w1.switch()
if __name__ == '__main__':
   w1=greenlet(work1)
   w2=greenlet(work2)
   w1.switch()#先执行第一个任务
gevent
#自动切换的协程(上面代码太麻烦) pip install gevent
from gevent import monkey
monkey.patch_all() #将系统耗时操作转换为能识别的耗时操作
import gevent
import time
def work1():
   while(True):
       print("work1 start")
       time.sleep(1)
       #gevent.sleep(1) 只识别这个为耗时操作
def work2():
   while(True):
       print("work2 start")
       time.sleep(1)
       #gevent.sleep(1) 只识别这个为耗时操作
if __name__ == '__main__':
   w1=gevent.spawn(work1)
   w2=gevent.spawn(work2)
   w1.join()
   w2.join()
进程线程协程总结
#多进程 CPU密集 多进程通信成本高
#多线程 网络 磁盘 数据库 I/O密集 高并发 加索问题 返回的数据是无序的
#多协程 网络I/O密集较好 CPU和磁盘IO的时候性能较低  高并发 返回的数据是有序的
#最好:进程+协程
posted @ 2022-11-26 14:29  Kotlin  阅读(31)  评论(0编辑  收藏  举报
Live2D