18 python --多線程

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函數。python

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @File    : demon1.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()
View Code


2. 線程鎖
經過threading.Lock()來建立鎖,函數在執行的只有先要得到鎖,左後執行完之後要釋放鎖:
with lock:
lock.acquire()
lock.release()
實例:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
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()bootstrap

import threading
import time


def worker(name, lock):
    with lock:
        print("start {0}".format(name))
        time.sleep(5)
        print("end {0}".format(name))

# with lock:
# lock.acquire()
# 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.")
View Code

 

3. 線程共享變量
多線程和多進程不一樣之處在於多線程自己就是能夠和父進程共享內存的,這也是爲何其中一個線程掛掉之後,爲何其餘線程也會死掉的道理。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
l = list()
l += range(1, 10)
def worker():
    l.append("ling")
    l.append("shang")
    l.append("hello")
if __name__ == "__main__":
    t = threading.Thread(target=worker)
    t.start()
    print(l)數組

import threading


def worker(l):
    l.append("ling")
    l.append("huo")
    l.append("wang")

if __name__ == "__main__":
    l = list()
    l += range(1, 10)
    print(l)
    t = threading.Thread(target=worker, args=(l,))
    t.start()
    print(l)
View Code

4. 線程池
經過傳入一個參數組來實現多線程,而且它的多線程是有序的,順序與參數組中的參數順序保持一致。
安裝包:
pip install threadpool

調用格式:
from threadpool import *
pool = ThreadPool(poolsize)
requests = makeRequests(some_callable, list_of_args, callback)
[pool.putRequest(req) for req in requests]
pool.wait()多線程

import threadpool


def hello(m, n, o):
    """"""
    print "m = %s, n = %s, o = %s" % (m, n, o)


if __name__ == '__main__':
    # 方法1
    lst_vars_1 = ['1', '2', '3']
    lst_vars_2 = ['4', '5', '6']
    func_var = [(lst_vars_1, None), (lst_vars_2, None)]
    # 方法2
    dict_vars_1 = {'m': '1', 'n': '2', 'o': '3'}
    dict_vars_2 = {'m': '4', 'n': '5', 'o': '6'}
    func_var = [(None, dict_vars_1), (None, dict_vars_2)]

    pool = threadpool.ThreadPool(2)
    requests = threadpool.makeRequests(hello, func_var)
    [pool.putRequest(req) for req in requests]
    pool.wait()
View Code
相關文章
相關標籤/搜索