【发布时间】:2019-09-19 06:36:50
【问题描述】:
我有两个函数 f1 和 f2 在这两个函数内的循环中递增一个整数特定次数。
我用两种方式调用这些函数。
1) 一个接一个,即先f1 然后f2。
2)创建线程t1运行函数f1和线程t2运行函数f2。
在下面的代码中,我已经尝试了两种方式。
from threading import Thread
import time
import datetime
from queue import Queue
def f1(a):
for i in range(1,100000000):
a+=1
return a
def f2(a):
for i in range(1,100000000):
a+=1
return a
if __name__ == '__main__':
que1 = Queue()
que2 = Queue()
# t2 = Thread(target=f1(a),name='t2')
a = 0
s_t = time.time()
print('Value of a, before calling function f1: ',a)
a=f1(a)
print('Value of a, after calling function f1: ',a)
a = 0
print('Value of a, before calling function f2: ',a)
a=f2(a)
print('Value of a, after calling function f2: ',a)
print('Time taken without threads: ',datetime.timedelta(seconds=time.time()-s_t))
s_t = time.time()
a = 0
print('Value of a, before calling function f1 through thread t1: ',a)
t1 = Thread(target=lambda q, arg1: q.put(f1(arg1)), args=(que1,a),name = 't1')
print('Value of a, before calling function f2 through thread t2: ',a)
t2 = Thread(target=lambda q, arg1: q.put(f2(arg1)), args=(que2,a),name = 't2')
t1.start()
t2.start()
t1.join()
print('Value of a, after calling function f1 through thread t1: ',que1.get())
t2.join()
print('Value of a, after calling function f2 through thread t2: ',que2.get())
print('Time taken with threads: ',datetime.timedelta(seconds=time.time()-s_t))
预期线程完成工作的速度比一个接一个地调用函数要快,但这里不是这样。
这是输出
Value of a, before calling function f1: 0
Value of a, after calling function f1: 99999999
Value of a, before calling function f2: 0
Value of a, after calling function f2: 99999999
Time taken without threads: 0:00:07.623239
Value of a, before calling function f1 through thread t1: 0
Value of a, before calling function f2 through thread t2: 0
Value of a, after calling function f1 through thread t1: 99999999
Value of a, after calling function f2 through thread t2: 99999999
Time taken with threads: 0:00:27.274876
出了什么问题?
【问题讨论】:
-
在
python中,只有singlethread可以在time处运行,因为GIL(Global Interpreter Lock)。所以你运行threads forcpu密集操作是uselessinpython -
@hansolo 你能建议一个解决方法吗?
-
您可以使用
concurrent.futures.ProcessPoolExecutor作为解决方法
标签: python multithreading parallel-processing