Multithreading in a loop - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Multithreading in a loop (/thread-4262.html) |
Multithreading in a loop - valtih - Aug-03-2017 I tried the following to create two worker processes import threading for i in range(0, 2): def spawnAWorker(): printf("%s", i) #os.system('start cmd /K ' + workerCmd) threading.Thread(target=lambda: spawnAWorker()).start()The problem is that printf prints me 1 two times instead of 0 and 1 Why? What can I do to start the first worker with id 0 and another with id 1? RE: Multithreading in a loop - valtih - Aug-03-2017 I have discovered that the problem goes away if I do not start the threads immediately: def spawnAWorker(i): printf("%s", i) #os.system('start cmd /K ' + workerCmd) threads = map(lambda i: threading.Thread(target=lambda: spawnAWorker(i)),range(0,2)) for t in threads: t.start()But, I see a problem here as well. If range is larger, say (0,100), I do not see all numbers printed. Some threads do not start. I have to inject a delay for t in threads: t.start() time.sleep (1) ## this sucks but some threads do not start if I launch them all at the same timeif I want all threads to start. I want more deterministic solution. RE: Multithreading in a loop - nilamo - Aug-03-2017 Do you ever .join() on the threads, to wait for them to finish? Maybe the main thread finishes before all the sub-threads get started. RE: Multithreading in a loop - valtih - Aug-03-2017 You are right! |