#1、开启线程: from threading import Thread import os def func(): print('func',os.getpid()) t = Thread(target=func) t.start() print(os.getpid()) # func 10452 #start之后马上执行func,说明开启线程很快。 # 10452 #2、主线程跟子线程异步:func睡眠1秒,但是最下面的打印还是会很快打印出来,说明各自干自己的事情,属于异步。 from threading import Thread import os import time def func(): #子线程 time.sleep(1) print('func',os.getpid()) t = Thread(target=func) t.start() print(os.getpid()) #主线程 # 4616 # func 4616 #3、开启多线程:异步: from threading import Thread import os import time def func(): time.sleep(1) print('func',os.getpid()) for i in range(6): t = Thread(target=func) t.start() print(os.getpid()) # 设置join让上面代码的主线程阻塞,等待子线程结束后才结束(先执行子线程代码): from threading import Thread import time import os def func(): time.sleep(1) print('func',os.getpid()) thread_l = [] for i in range(3): t = Thread(target=func) t.start() thread_l.append(t) [t.join() for t in thread_l] #相当于for t in thread_l:t.join(),让所有子线程先start执行,最后才设置join, #可以一次性得到结果,下面主线程的代码和子线程各自干自己的事情,属于异步。 print(os.getpid()) # func 14808 # func 14808 # func 14808 # 14808 #下面代码属于同步: from threading import Thread import time import os def func(): time.sleep(1) print('func',os.getpid()) for i in range(3): t = Thread(target=func) t.start() t.join()#join写在for里面,每开启一个子线程,都让主线程等待,按顺序执行,属于同步。 print(os.getpid()) #4、验证在一个进程里面,线程之间的数据是共享的:利用这个特点就可以计算出线程的数量: # 下面例子的进程id是一样的,说明系统调度了一个进程去执行一个任务,而这个任务分成了5个部分来执行。 from threading import Thread import os class MyThread(Thread): count = 0 #静态属性 def __init__(self,arg1): super().__init__() self.arg1 = arg1 def run(self): MyThread.count += 1 print('run',self.arg1,os.getpid()) for i in range(5): t = MyThread(i) t.start() print(t.count) #打印出对象属性是5,说明线程之间的数据是共享的。 # run 0 5948 # run 1 5948 # run 2 5948 # run 3 5948 # run 4 5948 #pid一样,说明所有线程都在同一个进程里面。 # 5 #5、打印出线程名字(name)、线程id(ident)、线程列表、线程列表数量: import threading import time def func(i): #线程名字(name)、线程id(ident) time.sleep(0.5) #睡眠一下让func执行久一点,因为这样下面才来得及统计线程列表数量。 print(i,threading.currentThread().name,threading.currentThread().ident) for i in range(5): t = threading.Thread(target=func,args=(i,)) t.start() print(threading.enumerate()) #返回正在运行的线程列表 print(len(threading.enumerate())) #6,线程列表数量是6,主线程1个,子线程5个。 print(threading.activeCount()) #6,线程列表数量是6。
day44-线程
猜你喜欢
转载自www.cnblogs.com/python-daxiong/p/12142765.html
今日推荐
周排行