thread 多线程
一、为什么重写mythread类里写了run()在main里没有调用,而调用了没有写的start()
start()让run()在新线程里面运行。你直接调用run()就是在当前线程运行了。
start()调用_thread的start_new_thread去运行一个bootstrap方法,在里面做一些准备工作后会调用run()
1.简单的多线程
from time import sleep, ctime
import threading
def fab(x):
sleep(5)
print 'fab', ctime()
if x < 3:
return 1
return (fab(x-1)+fab(x-2))
def sumx(x):
sleep(5)
print 'sumx', ctime()
if x < 2:
return 1
return (x+sumx(x-1))
def mulx(x):
sleep(5)
print 'mulx', ctime()
if x < 2:
return 1
return (x*mulx(x-1))
def main():
a = threading.Thread(target=fab, args=(1,))
sleep(1)
b = threading.Thread(target=sumx, args=(1,))
sleep(1)
c = threading.Thread(target=mulx, args=(1,))
a.start()
b.start()
c.start()
print threading.activeCount()
print threading.enumerate()
a.join()
b.join()
c.join()
if __name__ == '__main__':
main()
二、复杂的多线程
import threading
from time import sleep, ctime
loops = [4, 2]
class MyThread(threading.Thread):
def __init__(self, func, args, name=''):
threading.Thread.__init__(self)
self.name = name
self.func = func
self.args = args
def getResult(self):
return self.res
def run(self):
print 'starting', self.name, 'at:', ctime()
self.res = apply(self.func, self.args)
print self.name, 'finished at:', ctime()
def fib(x):
sleep(0.005)
if x < 2: return 1
return (fib(x-2) + fib(x-1))
def fac(x):
sleep(0.1)
if x <2: return 1
return (x * fac(x-1))
def sum(x):
sleep(0.1)
if x <2: return 1
return (x + sum(x-1))
funcs = [fib, fac, sum]
n = 12
def main():
nfuncs = range(len(funcs))
print '*** SINGLE THREAD'
for i in nfuncs:
print 'starting', funcs[i].__name__, 'at:', ctime()
print funcs[i](n)
print funcs[i].__name__, 'finished at:', ctime()
print '\n*** MULTIPLE THREADS'
threads = []
for i in nfuncs:
t = MyThread(funcs[i], (n,), funcs[i].__name__)
threads.append(t)
for i in nfuncs:
threads[i].start()
for i in nfuncs:
threads[i].join()
print threads[i].getResult()
print 'all DONE'
if __name__ == '__main__':
main()
三.多线程实例同时下载网页,args传入参数为元组
import urllib
import threading
url = ['http://www.baidu.com', 'http://pan.baidu.com', 'http://tieba.baidu.com']
def openurl(url, x):
urllib.urlretrieve(url, 'd:\\'+str(x)+'.txt')
def main():
print 'start...........'
list1 = []
loops = range(len(url))
for i in loops:
t = threading.Thread(target=openurl, args=(url[i],i))
list1.append(t)
for i in loops:
list1[i].start()
for i in loops:
list1[i].join()
print 'all down'
if __name__ == '__main__':
main()
四、实例化类继承类初始化,重写run()函数
import urllib
import threading
url = ['http://www.baidu.com', 'http://pan.baidu.com', 'http://tieba.baidu.com']
class downloader(threading.Thread):
def __init__(self, url, x):
threading.Thread.__init__(self)
self.url = url
self.x = x
def run(self):
urllib.urlretrieve(self.url, 'd:\\'+str(self.x)+'.txt')
for i in range(len(url)):
i = downloader(url[i], i)
i.start()