【发布时间】:2021-08-05 13:29:12
【问题描述】:
我如何使用多个线程并行地同时增加同一个变量,从而将总时间减少到原始同步过程的倍数?
例子:
num = 0
def incrementer():
for i in range(100):
global num
num += 1
for i in range(100):
th=Thread(target=incrementer)
th.start()
num
上面的代码确实给出了预期的结果(10000),但是所花费的时间比同步方法要长得多:
In [114]: %%timeit
...: num = 0
...: def incrementer():
...: for i in range(100):
...: global num
...: num += 1
...: for i in range(100):
...: th=Thread(target=incrementer)
...: th.start()
25.3 ms ± 2.27 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [113]: %%timeit
...: num = 0
...: for i in range(10000):
...: num += 1
596 µs ± 84.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
我预计多线程方法将花费同步方法的 1% 的时间...
我怎样才能使异步方法花费同步方法所用时间的 n 分之一来完成 n 个线程,或者这显然是不可能的?
【问题讨论】:
-
这能回答你的问题吗? python multi-threading slower than serial?
-
Python 不做真正的线程,除非你使用类似
multiprocessing包的东西。此外,您的基准测试包括设置线程的成本,这不一定是微不足道的,我怀疑它会主导您的结果。作为旁注,您的代码不是线程安全的。整数写入在 Python 中是原子的,但增量是两个操作(读取和写入),并且可以在两者之间中断。 -
实例化新线程的运行时开销远远超过函数执行所花费的时间
标签: python python-3.x multithreading asynchronous