python 多线程的启动与阻塞
程序员文章站
2022-05-02 12:53:13
...
import threading
t1=threading.Thread(target=func,args=iterable)
t2=threading.Thread(target=func,args=iterable)
创建一个新的进程很简单,func为想要进程执行的函数名,arg即为iterable
如func的参数为整数,传递参数的时候不能写成
t1=threading.Thread(target=func,args=3)
正确的写法为
#能用于for循环的即是iterable
t1=threading.Thread(target=func,args=(3,))
启动线程
import time
import threading
def hold1(limit):
i=0
while i<limit:
i+=1
print(t1.name,"is runing")
time.sleep(1)
print(t1.name,"is over")
def hold2(limit):
i=0
while i<limit:
i+=1
print(t2.name,"is runing")
time.sleep(1)
print(t2.name,"is over")
start_time=time.time()
t1=threading.Thread(target=hold1,args=(3,))
t2=threading.Thread(target=hold2,args=(6,))
t1.start()
t2.start()
print(threading.current_thread().name,"耗时",time.time()-start_time)
输出为:
Thread-1 is runing
Thread-2 is runing
MainThread 耗时 0.002000093460083008
Thread-1 is runing
Thread-2 is runing
Thread-1 is runing
Thread-2 is runing
Thread-1 is over
Thread-2 is runing
Thread-2 is runing
Thread-2 is runing
Thread-2 is over
可以看出主线程先于子线程结束,若要主线程等待子线程,则需要join()函数
在源代码的基础上,在t2.start()加入
t1.join()
t2.join()
则输出结果为:
Thread-1 is runing
Thread-2 is runing
Thread-2 is runing
Thread-1 is runing
Thread-2 is runing
Thread-1 is runing
Thread-2 is runing
Thread-1 is over
Thread-2 is runing
Thread-2 is runing
Thread-2 is over
MainThread 耗时 6.003343343734741