passwd passwd - 2 months ago 9
Python Question

Python Threads, why threads in two dimensions aren't work?

I have this script:

import threading
import time
import sys

def threadWait(d1, d2):
global number
time.sleep(1) # My actions
number = number+1 # Count of complete actions +1
sys.stdout.write("\033[K") # Clean line to the end.
sys.stdout.write(str(number)+" (Thread "+str(d1)+", "+str(d2)+") done"+"\r") # Write number and carriage return.
sys.stdout.flush()

number = 0 # Count of complete actions
threadsToJoin = []

dimension1 = [] # Main action task.
for i in range(50): # I have 50 "Main Actions" I need to do in parallel threads.
d1 = i
dimension2 = [] # I need to do each "Main Action" in 10 threads.
for n in range(10):
d2 = n
dimension2.append(threading.Thread(target=threadWait, args=(d1,d2)))

dimension1.append(dimension2)




for item in dimension1:
for items in dimension2:
# But I can't do more than 100 Threads at once.
while True:
# Analogue of BoundedSemaphore.
if (int(threading.activeCount()) < 100):
items.start()
threadsToJoin.append(items)
break
else:
continue

for this in threadsToJoin:
this.join()


But I'm getting an error about "Thread can't be started twice". But when I'm adding all threads in
dimension2
and running like this:

for item in dimension2:
# But I can't do more than 100 Threads at once.
while True:
# Analogue of BoundedSemaphore.
if (int(threading.activeCount()) < 100):
item.start()
break
else:
continue


Everythin is going good as excpected. What is wrong with the first example and how can I do the whole threading(multithreading) as they do it nowadays?

Answer

What do you mean here:

for item in dimension1:
    for items in dimension2:

Do you mean:

for item in dimension1:
    for items in item:

I suppose you don't want to run threads in [dimension2] every cycle.

Comments