Home > Software design >  Python Thread State Shared Between Loops?
Python Thread State Shared Between Loops?

Time:10-25

I am trying to create a series of threads from a for-loop to kick off parallelized tasks. The problem is I don't know how to keep the variable states in each iteration from being shared upon execution. Take this simple example where I print the values 0 through 9 on 10 different threads respectively.

import threading
from time import sleep

threads = []

for i in range(0,10):

    def op():
        sleep(3)
        print(i)

    threads.append(threading.Thread(target = op))

# start threads
for th in threads:
    th.start()

# join threads
for th in threads:
    th.join()

My output is all 9's because that is the last iteration. How do I isolate my state in each iteration so I get the numbers 1 through 9? Rather than all 9's?

CodePudding user response:

The reason why every thread is printing the same value is because by the time the threads start, i is already 9 and every thread sees the same variable.

If the goal is to make sure each thread gets a unique value to work on, an argument can be passed to the thread function. (this example also moves the definition of op outside the loop).

def op(n):
    sleep(3)
    print(n)

for i in range(0,10):
    threads.append(threading.Thread(target = op, args=(i,)))

That will print the values 0 through 9 (though not necessarily in order, because threads run indeterminately).

If there's some aspect of this I've still misunderstood, please clarify.

  • Related