Python中提供threading模块来对多线程的操作
线程是引用程序中工作的最小单元
线程的实现有2种方式
1、讲要执行的方法作为参数传给Thread的构造方法
2、从Thread继承,重写run()
#!/usr/bin/env python #coding:utf8 import threading def worker(n): print "start wworker {0}".format(n) class MyThread(threading.Thread): def __init__(self,args): super(MyThread,self).__init__() self.args = args def run(self): print "start MyThread{0}".format(self.args) if __name__ == "__main__": for i in xrange(1,6): t1 = threading.Thread(target=worker,args=(i,)) t1.start() t1.join() for x in xrange(6,11): t2 = MyThread(x) t2.start()
执行结果:
start worker 1 start worker 2 start worker 3 start worker 4 start worker 5 start MyThread6 start MyThread7 start MyThread8 start MyThread9 start MyThread10
线程锁通过threading.Lock创建,函数执行过程只有获得锁,执行完要释放所
with lock 或
lock.acquire()
lock.release()
import threading import time def worker(name,lock): with lock: print "start {0} time:{1}".format(name,time.time()) time.sleep(5) print "end {0} time:{1}".format(name, time.time()) if __name__ == "__main__": lock = threading.Lock() t1 = threading.Thread(target=worker,args=("worker1",lock)) t2 = threading.Thread(target=worker,args=("worker2",lock)) t1.start() t2.start() print "main end ,time: {0}".format(time.time()) print "main end"
运行结果:
start worker1 time:1512184912.0 main end ,time: 1512184912.0 end worker1 time:1512184917.0 start worker2 time:1512184917.0 end worker2 time:1512184922.0