python 多线程
python 多线程
科技在发展,时代在进步,我们的 CPU 也越来越快,CPU 抱怨,P 大点事儿占了我一定的时间,其实我同时干多个活都没问题的;于是,操作系统就进入了多任务时代。我们听着音乐吃着火锅的不在是梦想。
python 提供了两个模块来实现多线程 thread 和 threading ,thread 有一些缺点,在 threading 得到了弥补,为了不浪费你和时间,所以我们直接学习 threading 就可以了。
示例代码
#coding=utf-8
import threading
from time import ctime,sleep
def music(func):
for i in range(2):
print( "I was listening to %s. %s" %(func,ctime()))
sleep(1)
def move(func):
for i in range(2):
print ("I was at the %s! %s" %(func,ctime()))
sleep(1)
threads = []
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'阿凡达',))
threads.append(t2)
if __name__=="__main__":
for t in threads:
t.setDaemon(True)
t.start()
for t in threads:
t.join()
print ("all is over. %s"%(ctime()))