How can I use multiple threads to increment same variable concurrently in parallel so that the total amount of time taken is reduced to that multipleth of the original synchronous process would take?
Example:
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
The above code does give the intended result (10000), but the time taken is much greater than the synchronous approach:
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)
I was expecting the multi-threading approach to take 1 percent of time taken by the synchronous approach...
How can I make the asynchronous approach take nth of time of the time taken by synchronous approach to complete for n threads, or is it plainly impossible?