Day13 线程与进程
1.threading模块
–单线程执行
enumerate() 函数:
用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标。可以用enumerate()来查看线程的进行程度。
–当出现调用thread时,不会创建线程,线程会跑到test1里去执行
def main():
t1=threading.Thread(target=test1)
print(threading.enumerate())
[<_MainThread(MainThread, started 4445822400)>]
–当调用start后,才算创建了线程以及运行线程
t1=threading.Thread(target=test1)
print(threading.enumerate())
t1.start()
print(threading.enumerate())
[<_MainThread(MainThread, started 4445822400)>, <Thread(Thread-1, started 123145407184896)>]
2.继承thread类创建线程
定义一个子类,通过继承threading.Thread,可以完成线程的封装。
import threading
import time
class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg="I'm "+self.name+' @'+str(i)
print(msg)
def login(self):
print("这是登录。。。。。。")

本文介绍了Python中的线程与进程,包括threading模块的使用,如enumerate()函数,线程的启动,以及如何继承threading.Thread创建线程。讨论了多线程共享全局变量的问题,提出了互斥锁作为解决方案,并提到了死锁及其避免方法。最后,对比了多线程与协程的执行效率,指出协程在执行效率和资源管理上的优势。
最低0.47元/天 解锁文章
269

被折叠的 条评论
为什么被折叠?



