Python中提供了threading模块来对多线程的操作,
1. 多线程实例
线程是应用程序中工作的最小单元。
多线程是现实有两种方式:
方法一:将要执行的方法作为参数传给Thread的构造方法(和多进程类似)
t = threading.Thread(target=action,
args=(i,))
方法二:从Thread继承,并重写run()
看源码:
P = threading.Thread
p.start() à_start_new_thread(self.__bootstrap,
()) àself.__bootstrap_inner() à
self.run()
try:
if self.__target:
self.__target(*self.__args,
**self.__kwargs)
所以如果重写了run,就直接调用run的函数了,如果run没有重新,就调用target函数。
代码实例如下:
-
#!/usr/bin/env python
-
# -*- coding:utf-8 -*-
-
# Author :Alvin.xie
-
# @Time :2017-12-13 11:35
-
# @file :10.py
-
-
-
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 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()
-
t2.join()
执行结果:
start worker1
start worker2
start worker3
start worker4
start worker5
start MyThread6
start MyThread7
start MyThread8
start MyThread9
start MyThread10
线程锁
通过threading.Lock()来创建锁,函数在执行的只有先要获得锁,左后执行完以后要释放锁:
with
lock:
lock.acquire()
lock.release()
-
#!/usr/bin/env python
-
# -*- coding:utf-8 -*-
-
# Author :Alvin.xie
-
# @Time :2017-12-13 10:50
-
# @file :9.py
-
-
-
import threading
-
import time
-
def worker(name, lock):
-
with lock:
-
print("start {0}".format(name))
-
time.sleep(5)
-
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()
执行结果:
start worker1
end worker1
start worker2
end worker2
阅读(1705) | 评论(0) | 转发(0) |