Bottom Page

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?
Quote
#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.
Quote
#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.
Quote
#4
You are right!
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Locks in Multithreading Chuonon 0 93 Oct-03-2019, 04:16 PM
Last Post: Chuonon
  Multithreading alternative MartinV279 1 176 Aug-01-2019, 11:41 PM
Last Post: scidam
  Multithreading with ssh connection harusin 6 2,219 Jul-10-2017, 11:40 AM
Last Post: harusin

Forum Jump:


Users browsing this thread: 1 Guest(s)