_thread实现线程
-
在Python程序中,可以通过两种方式来使用线程:使用函数或者使用类来包装线程对象。当使用thread模块来处理线程时,可以调用里面的函数start_new_thread()来生成一个新的线程。
-
1 _thread.start_new_thread ( function, args[, kwargs] )
- 其中function是线程函数;args表示传递给线程函数的参数,他必须是个tuple类型;kwargs 是可选参数。
-
1 import _thread 2 import time 3 def fun1(): 4 print('开始运行fun1') 5 time.sleep(4) 6 print('运行fun1结束') 7 def fun2(): 8 print('开始运行fun2') 9 time.sleep(2) 10 print('运行fun2结束') 11 if __name__ == '__main__': 12 print('开始运行') 13 #创建线程 14 _thread.start_new_thread(fun1,()) 15 _thread.start_new_thread(fun2,()) 16 time.sleep(7)
1 开始运行 2 开始运行fun1 3 开始运行fun2 4 运行fun2结束 5 运行fun1结束
正是江南好风景