多線程的簡單操作

多線程模板1

import time
import threadpool


# 使用線程移動文件
def move(each_img):
    print("each_img", each_img)
    time.sleep(1)


if __name__ == '__main__':
    start_time = time.time()
    all_img = range(100)
    task_pool = threadpool.ThreadPool(100)
    tasks = threadpool.makeRequests(move, all_img)
    for task in tasks:
        task_pool.putRequest(task)
    task_pool.wait()
    end_time = time.time()
    print('花費 %s time' % str(end_time - start_time))

多線程模板2  因爲多線程是共享全局變量的, 所以全局變量只要有一個線程改了。 另一個子線程進來的時候就會沿用已經被修改的全局變量。

import os
import shutil
import time
import threadpool
from threading import Lock


# 使用線程移動文件
def move(each_img):
    global num
    num += 1
    print("each_img", each_img)
    print("num", num)
    time.sleep(1)


if __name__ == '__main__':
    num = 0
    start_time = time.time()
    all_img = range(100)
    task_pool = threadpool.ThreadPool(100)
    tasks = threadpool.makeRequests(move, all_img)
    for task in tasks:
        task_pool.putRequest(task)
    task_pool.wait()
    end_time = time.time()
    print('花費 %s time' % str(end_time - start_time))

輸出結果:

多線程模板3 加上互斥鎖, 這樣全局變量就不會被共享了, 因爲每一個線程在進入的時候,這個進程的鎖沒有被釋放,其他的進程就不會進去。從而達到不共享變量,有序執行。

import os
import shutil
import time
import threadpool
from threading import Lock


# 使用線程移動文件
def move(each_img):
    print("each_img", each_img)
    global gl_num
    lock.acquire()
    gl_num += 1
    print(gl_num)
    lock.release()
    print("---------------------")


if __name__ == '__main__':
    lock = Lock()
    gl_num = 0
    start_time = time.time()
    all_img = range(50)
    task_pool = threadpool.ThreadPool(10)
    tasks = threadpool.makeRequests(move, all_img)
    for task in tasks:
        task_pool.putRequest(task)
    task_pool.wait()
    end_time = time.time()
    print('花費 %s time' % str(end_time - start_time))

輸出結果:

 

多線程主函數有多個參數:多一層包裝函數

# !/usr/bin/env Python3
# -*- coding: utf-8 -*-
# @Author   : zsc
# @FILE     : 多線程多個參數.py
# @Time     : 2020/2/26 17:19
# @Software : PyCharm

import threadpool
from threading import Lock


def main(a, b, c):
    # lock.acquire()
    print("a", a)
    print("b", b)
    print("c", c)
    print("-------------------")
    # lock.release()


def multi_wrapper(args):
    return main(*args)


def multi_wrapper_report(a, b, c):
    ls1 = [a, b, c]
    ls2 = [a, a, a]
    ls3 = [b, b, b]
    ls4 = [c, c, c]
    pool_list = [ls1, ls2, ls3, ls4]
    task_pool = threadpool.ThreadPool(10)
    tasks = threadpool.makeRequests(multi_wrapper, pool_list)
    [task_pool.putRequest(task) for task in tasks]
    task_pool.wait()


if __name__ == '__main__':
    lock = Lock()
    multi_wrapper_report(1, 100, 10000)

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章