【Python】多线程切图


使用多线程对图片进行处理
开启线程前需要获取到 图片名称列表
每个线程要做的事:图片读取、处理与绘制、保存

使用线程池(测试比进程池快20%)

import time
from concurrent.futures import ThreadPoolExecutor

def mysquare(s):		# 功能函数 平方
  time.sleep(0.5)
  print(f'i{s}', end='')
  return s*s		# 返回值可选 选择后返回值会一一按顺序给after

t0 = time.time()
executor = ThreadPoolExecutor(max_workers=10) #参数为线程数
data = list(range(100)) # 要处理的数据
after = []        # 处理完的数据,需要按照顺序返回
for i in executor.map(mysquare, data):
  after.append(i)
t1 = time.time()
print()
print('after:', after)
print(t1-t0)

线程池(功能函数多参数输入)

import time
from concurrent.futures import ThreadPoolExecutor
def mysquare(z):    # 变量解析函数 多变量输入
	return mysquare_real(z[0], z[1])
def mysquare_real(x, y):		# 实际功能函数 
  time.sleep(0.5)
  print(f'i{x*y}', end='')
  return x*y		# 返回值可选 选择后返回值会一一按顺序给after

t0 = time.time()
executor = ThreadPoolExecutor(max_workers=10) #参数为线程数
data = [] # 要处理的数据
for i in range(100):
  data.append((i,i+1))
after = []        # 处理完的数据,需要按照顺序返回
for i in executor.map(mysquare, data):
  after.append(i)
t1 = time.time()
print()
print('after:', after)
print(t1-t0)

自己动态开多线程处理(繁琐,更适合不同线程完成不同的任务)

import time
from tqdm import tqdm
from threading import Lock,Thread
def func(m):  # 处理函数
  # print('handling func', m)
  time.sleep(0.5)
  # print('handled func', m)
n = 100
pbar = tqdm(total=n)
t1 = time.time()
Lock = Lock()
class myThread(Thread):  # 继承父类threading.Thread
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
    def run(self):  # 把要执行的代码写到run函数里面 线程在创建后会直接运行run函数
        print("Starting " + self.name)
        while True:
          Lock.acquire()
          global n
          if n==0: 
            Lock.release() 
            break;
          n-=1
          temp = n
          pbar.update(1)
          Lock.release() 
          func(temp)
        print("Exiting " + self.name)

th_num = 12 # 线程数
l = []
for i in range(th_num):
    p = myThread(i)
    l.append(p)
    p.start()

# 等待所有线程结束
for p in l:
    p.join()
pbar.close()
t2 = time.time()
print("Exiting Main Thread", t2-t1)

使用进程池

import time
from functools import partial
from multiprocessing import Process, Pool

t0 = time.time()
def mysquare(s):		# 功能函数 平方
  time.sleep(0.5)
  print(f'i{s}', end='')
  return s*s		# 返回值可选 选择后返回值会一一按顺序给after
pool = Pool(10)   # 参数为进程数
data = list(range(100)) # 要处理的数据
after = pool.map(mysquare, data) # 并将函数的返回值映射到r 按照l的顺序
pool.close()
pool.join()
t1 = time.time()
print()
print('after:', after)
print(t1-t0)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值