我有这样的脚本:Python线程,为什么两个维度的线程都不起作用?
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()
但我发现了大约一个错误的“线程无法启动两次”。但是,当我将所有线程dimension2
和运行这样的:
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
对一切会好excpected。第一个例子有什么问题,我如何像现在这样完成整个线程(多线程)?
这是如此愚蠢的错误0_O对不起,有时我需要小睡一下才能清理我的思维。 – passwd