Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Multithreading in a loop
#1
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?
Reply
#2
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.
Reply
#3
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.
Reply
#4
You are right!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  multithreading Hanyx 4 1,319 Jul-29-2022, 07:28 AM
Last Post: Larz60+
Question Problems with variables in multithreading Wombaz 2 1,320 Mar-08-2022, 03:32 PM
Last Post: Wombaz
  Multithreading question amadeok 0 1,772 Oct-17-2020, 12:54 PM
Last Post: amadeok
  How can i add multithreading in this example WoodyWoodpecker1 3 2,503 Aug-11-2020, 05:30 PM
Last Post: deanhystad
  matplotlib multithreading catosp 0 2,943 Jul-03-2020, 09:33 AM
Last Post: catosp
  Multithreading dynamically syncronism Rodrigo 0 1,528 Nov-08-2019, 02:33 AM
Last Post: Rodrigo
  Locks in Multithreading Chuonon 0 1,836 Oct-03-2019, 04:16 PM
Last Post: Chuonon
  multithreading issue with output mr_byte31 4 3,193 Sep-11-2019, 12:04 PM
Last Post: stullis
  Multithreading alternative MartinV279 1 2,776 Aug-01-2019, 11:41 PM
Last Post: scidam
  using locks in multithreading in python3 srm 2 3,663 Jul-13-2019, 11:35 AM
Last Post: noisefloor

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020