标签:python
一、多线程实例线程时应用程序中工作的最小单位,python中提供了threading模块来对多线程操作,一般多核cpu采用多进程方式,单核才采用多线程方式
方法一:
将要执行的方法作为参数传给thread的构造方法(和多进程类似),如下:
t = threading.Thread(target=action,args=(i,))
方法二:
从Thread继承,并重写run()
例子:
import threading def worker(n): print("start worker{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 range(1,6): t1 = threading.Thread(target=worker,args=(i,)) t1.start() t1.join() for x in range(6,11): t2 = Mythread(x) t2.start() t2.join()
运行结果:
start worker1
start worker2
start worker3
start worker4
start worker5
start Mythread 6
start Mythread 7
start Mythread 8
start Mythread 9
start Mythread 10
二、线程锁
通过threading.Lock()来创建锁,函数在执行前先获得锁,执行后释放锁,和进程锁相似
with lock:
lock.acquire()
lock.release()
例子:
import threading import time def worker(name,lock): with lock: print("start {0}".format(name)) time.sleep(3) print("end {0}".format(name)) 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")
运行结果:
start worker1
main end
end worker1
start worker2
end worker2
说明:只有线程1结束以后,线程2才能执行
三、线程共享变量
多线程和多进程不同之处在于多线程本身就是可以和父进程进行共享内存的,这也是为什么其中一个线程挂掉之后,其他线程也死掉的原因
例子:
import threading def worker(l): l.append("hello") l.append("china") l.append("world") if __name__ == "__main__": l = list() l += range(1,5) print(l) t = threading.Thread(target=worker,args=(l,)) t.start() print(l)
运行结果:
[1, 2, 3, 4]
[1, 2, 3, 4, 'hello', 'china', 'world']
标签:python
原文地址:http://blog.51cto.com/huangzp/2050450