标签:python
一、非线程执行(普通的执行)
1、非线程运行,简单代码如下
#_*_coding:utf-8_*_ import time import threading a = [] b = [] def func1(): print "func1 start %s" % time.ctime() alist = ["192.168.1.100","192.168.1.120","192.168.1.134","192.168.1.213"] for i in alist: a.append(i) time.sleep(3) def func2(): print "func2 start %s" % time.ctime() blist = ["pc1","pc2","pc45","pc23"] for i in blist: b.append(i) time.sleep(2) func1() func2() print a,b
2、执行结果
/usr/bin/python2.7 /home/toby/PycharmProjects/SOMS/test.py
func1 start Tue Feb 28 03:03:44 2017
func2 start Tue Feb 28 03:03:47 2017
[‘192.168.1.100‘, ‘192.168.1.120‘, ‘192.168.1.134‘, ‘192.168.1.213‘] [‘pc1‘, ‘pc2‘, ‘pc45‘, ‘pc23‘]
3、对执行结果简单分析
3分44秒运行函数func1,运行完之后,那么在3分47秒开始运行函数func2。也就是说这是典型的顺序执行。
二、多线程运行
1、多线程的代码如下
#_*_coding:utf-8_*_ import time import threading a = [] b = [] def func1(): print "func1 start %s" % time.ctime() alist = ["192.168.1.100","192.168.1.120","192.168.1.134","192.168.1.213"] for i in alist: a.append(i) time.sleep(3) def func2(): print "func2 start %s" % time.ctime() blist = ["pc1","pc2","pc45","pc23"] for i in blist: b.append(i) time.sleep(2) thr = [] t1 = threading.Thread(target=func1,) thr.append(t1) t2 = threading.Thread(target=func2,) thr.append(t2) for i in thr: i.setDaemon(True) i.start() t1.join() t2.join() print a,b
2、多线程执行结果
/usr/bin/python2.7 /home/toby/PycharmProjects/SOMS/test.py
func1 start Tue Feb 28 03:09:32 2017
func2 start Tue Feb 28 03:09:32 2017
[‘192.168.1.100‘, ‘192.168.1.120‘, ‘192.168.1.134‘, ‘192.168.1.213‘] [‘pc1‘, ‘pc2‘, ‘pc45‘, ‘pc23‘]
3、执行结果简单分析
线程t1调用函数func1,线程t2调用函数func2,根据运行时间来看,这两个线程是在同一时间运行。
注意:
join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。 join()方法的位置是在for循环外的,也就是说必须等待for循环里的两个进程都结束后,才去执行主进程。不然,会由于主线程执行完结束,从而导致子线程也终止。
本文出自 “运维交流Q群:223843163” 博客,请务必保留此出处http://freshair.blog.51cto.com/8272891/1902089
标签:python
原文地址:http://freshair.blog.51cto.com/8272891/1902089