Python Forum

Full Version: Multithreading in a loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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 Huh Why? What can I do to start the first worker with id 0 and another with id 1?
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 time
if I want all threads to start. I want more deterministic solution.
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.
You are right!