多线程
协程
IO模型
多线程
#线程的PID与主进程PID一致 from threading import Thread from multiprocessing import Process import os def task(): print(‘%s is running‘ %os.getpid()) if __name__ == ‘__main__‘: t1=Thread(target=task,) t2=Thread(target=task,) # t1=Process(target=task,) # t2=Process(target=task,) t1.start() t2.start() print(‘主‘,os.getpid())
#多线程共享一个进程内的资源 from threading import Thread from multiprocessing import Process n=100 def work(): global n n=0 if __name__ == ‘__main__‘: # p=Process(target=work,) # p.start() # p.join() # print(‘主‘,n) t=Thread(target=work,) t.start() t.join() print(‘主‘,n)
#开启线程的两种方式 #开启线程的方式一:使用替换threading模块提供的Thread from threading import Thread from multiprocessing import Process def task(): print(‘is running‘) if __name__ == ‘__main__‘: t=Thread(target=task,) # t=Process(target=task,) t.start() print(‘主‘) #开启线程的方式二:自定义类,继承Thread from threading import Thread from multiprocessing import Process class MyThread(Thread): def __init__(self,name): super().__init__() self.name=name def run(self): print(‘%s is running‘ %self.name) if __name__ == ‘__main__‘: t=MyThread(‘egon‘) # t=Process(target=task,) t.start() print(‘主‘)
#多线程共享同一进程内地址空间的练习 #三个任务,一个接收用户输入,一个将用户输入的内容格式化成大写,一个将格式化后的结果存入文件 from threading import Thread msg_l=[] format_l=[] def talk(): while True: msg=input(‘>>: ‘).strip() msg_l.append(msg) def format(): while True: if msg_l: data=msg_l.pop() format_l.append(data.upper()) def save(): while True: if format_l: data=format_l.pop() with open(‘db.txt‘,‘a‘) as f: f.write(‘%s\n‘ %data) if __name__ == ‘__main__‘: t1=Thread(target=talk) t2=Thread(target=format) t3=Thread(target=save) t1.start() t2.start() t3.start()
#Thread对象其他相关的属性或方法 from threading import Thread,activeCount,enumerate,current_thread import time def task(): print(‘%s is running‘ %current_thread().getName()) time.sleep(2) if __name__ == ‘__main__‘: t=Thread(target=task,) t.start() t.join() print(t.is_alive()) print(t.getName()) print(enumerate()) print(‘主‘) print(activeCount())
协程
IO模型
时间: 2024-10-13 00:28:33