多线程的简单操作

多线程模板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)

 

 

 

 

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