1

My code

import time
from multiprocessing.pool import ThreadPool
from concurrent.futures import ThreadPoolExecutor
def print_function(tests):
    while True:
        print tests
        time.sleep(2)


executor = ThreadPoolExecutor(max_workers=2)

for i in range(5):
    a = executor.submit(print_function(i))

output 0 0 0 0 0 0 0 0...

but I want out 012345, 012345, 012345...

How can I do this ?

5
  • 3
    You are calling your function yourself. You should let the executor do that for you. Did you mean: a = executor.submit(print_function, i)?
    – quamrana
    Commented Jun 14, 2021 at 13:45
  • this is not important I try executor.submit(print_function, i)
    – user16223270
    Commented Jun 14, 2021 at 13:47
  • Can you clarify what you are trying to achieve by using threading/multiprocessing to get "012345, 012345, 012345, ..."? Both are means of preemptive concurrency, meaning there is no ordering whatsoever between tasks. The tasks may run in arbitrary order, so each block will give a seemingly random order like "421350"; after many (many) cycles, the time.sleep will not be sufficient to keep blocks coherent and you might get "0341205". Basically if you want such order, then threading/multiprocessing is very, very likely the wrong tool. Commented Jun 14, 2021 at 14:20
  • @JohnettaPeterson: you have tried to edit my answer. Please post a comment instead. You can only edit your own posts (the question), not everyone's posts. (That will change over time; once you have enough reputation, you can edit other people's posts). Commented Jun 14, 2021 at 14:37
  • I have rolled back yet another edit that erased significant parts of the question. Please be mindful not to destroy questions via edits. It is fine to rework a question to improve it, but it should still be about the fundamentally same issue and not invalidate existing answers. Commented Jun 15, 2021 at 14:27

1 Answer 1

2

In the line

a = executor.submit(print_function(i))
                    ^^^^^^^^^^^^^^^^^

you are calling the function already. Since it has a while True, it will never finish and thus submit() will never be reached.

The solution is to pass the function as a reference and the argument separately:

a = executor.submit(print_function, i)

However, notice that you will not get the output you like (012345), since a) the range will stop at 4 and b) you kick off only 2 workers and c) the operating system will choose which process to run, so that will be seemingly random (more like 310254).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.