python多线程threading

最近看了双线性插值的算法,想要自己实现以下,于是写了一个程序,测了下时间,将1080*1564的一张证件照通过插值resize到600*800花了15s....

于是想要用threading多线程来做,3个子线程对3个通道分别做插值,岂不是速度会提升3倍?结果还是15s,让我实在想不通,最后查了下关于python多线程的问题,才明白过来

from PIL import Image
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np 
import math
import os
from threading import Thread
from multiprocessing import Process


img_path = r'C:\Users\king\Pictures\简历\微信图片_20190731154219.jpg'
img_arr = np.array(Image.open(img_path), np.uint8)	

target_size = (800, 600, 3)
global resized_img
resized_img = np.zeros(target_size)
cur_size = img_arr.shape
ratio_x, ratio_y = target_size[0] / cur_size[0], target_size[1] / cur_size[1]

def cal(i, j, x, y, c):
	global resized_img
	# print('this is the thread {}'.format(c))

	t_left_x, t_left_y = math.floor(x), math.floor(y)

	p1 = (t_left_x+1 - x)*img_arr[t_left_x, t_left_y, c] + (x - t_left_x)*img_arr[t_left_x+1, t_left_y, c]
	p2 = (t_left_x+1 - x)*img_arr[t_left_x, t_left_y+1, c] + (x - t_left_x)*img_arr[t_left_x+1, t_left_y+1, c]

	v = (t_left_y+1 - y)*p1 + (y - t_left_y)*p2

	resized_img[i, j, c] = v


def bilinear(c):

	a = [cal(i, j, i/ratio_x, j/ratio_y, c) for i in range(target_size[0]) for j in range(target_size[1])]	


if __name__ == '__main__':
	start = datetime.now()
	threads = []
	for c in range(3):
		t = Thread(target=bilinear, args=(c,))
		threads.append(t)
		t.start()		

	for t in threads:
		t.join()
	# print(resized_img)

	end = datetime.now()

	seconds = (end-start).seconds
	print('process cost {}s'.format(seconds))

	resized_show = Image.fromarray(resized_img.astype(np.uint8))
	plt.imshow(resized_show)
	plt.show()

	

因为在python的世界里,不得不提GIL(Global  Interpreter Lock),由于其存在,每个CPU时间内只能执行一个线程,所以单核CPU下的python多线程只能处理并发而不能处理并行。

在python中, GIL的释放逻辑是当遇到IO操作或者ticks技术达到阈值,GIL释放,其他线程被唤醒,将要竞争拿到GIL上CPU运行,这种竞争模式可能是先来先服务,短作业优先或者时间片轮转... 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值