多线程适用于IO密集型,多线程实现方式有两种,详见下方例子
例子:
import threading
class MyThread(threading.Thread):
def __init__(self, args):
#使用super写法,按照父类.方法的方式直接重写
super(MyThread, self).__init__()
self.args = args
def run(self):
print ("start MyThread {0}".format(self.args))
def worker(n):
print ("start worker{0}".format(n))
if __name__ == "__main__":
#同多进程使用方法
for i in xrange(1, 6):
#使用threading.Thread指定函数和参数,多线程执行
t1 = threading.Thread(target=worker, args=(i,))
#开始多线程执行
t1.start()
t1.join()
#重写threading.Thread中的run方法实现多线程
for x in xrange(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
多线程锁
多线程锁的两种写法,详见下面两个例子
例子:
import threading
import time
def worker(name, lock):
#with写法会自动获得锁并自动释放锁,与
with lock:
print ("start {0}".format(name))
time.sleep(2)
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
例子:
import threading
import time
def worker(name, lock):
#获取线程锁
lock.acquire()
#捕获异常
try:
print ("start {0}".format(name))
time.sleep(2)
print ("end {0}".format(name))
except Exception as e:
raise e
finally:
#释放线程锁
lock.release()
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
线程的共享内存
线程缺点是有一个线程崩溃时所有剩余线程均会崩溃
例子:
#线程共享内存
import threading
def worker(l):
l.append("a")
l.append("b")
l.append("c")
if __name__ == "__main__":
l = list()
l += xrange(1,6)
print (l)
t = threading.Thread(target=worker, args=(l,))
t.start()
print (l)
输出:
a1 b2 c3
a4 b5 c6
线程池
例子:
#此包为第三方包,需要使用pip安装
import threadpool
def test1(a, b, c):
print("a{0} b{1} c{2}".format(a, b, c))
if __name__ == "__main__":
#the way one
lst_vars_1 = ['1', '2', '3']
lst_vars_2 = ['4', '5', '6']
func_var = [(lst_vars_1, None), (lst_vars_2, None)]
# the way two
dict_vars_1 = {'a':'1', 'b':'2', 'c':'3'}
dict_vars_2 = {'a':'4', 'b':'5', 'c':'6'}
func_var = [(None, dict_vars_1), (None, dict_vars_2)]
pool1 = threadpool.ThreadPool(2)
request = threadpool.makeRequests(test1, func_var)
[pool1.putRequest(req) for req in request]
pool1.wait()
共同学习,写下你的评论
评论加载中...
作者其他优质文章