Python线程,为什么两个维度的线程不起作用?

时间:2016-10-01 13:55:18

标签: python multithreading

我有这个脚本:

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

Everythin的表现和预期一样好。第一个例子出了什么问题,我怎么能像现在这样做整个线程(多线程)?

2 个答案:

答案 0 :(得分:2)

你在这里是什么意思:

for item in dimension1:
    for items in dimension2:

你的意思是:

for item in dimension1:
    for items in item:

我想你不想在每个周期[dimension2]中运行线程

答案 1 :(得分:2)

你的嵌套循环迭代了你想象的其他东西:

for item in dimension1:
    for items in dimension2:
        # But I can't do more than 100 Threads at once.

问自己一个问题dimension2定义在哪里?
如果你觉得很难弄清楚,这就是答案:

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.

在程序离开第一个嵌套循环(你在其中创建“维”的那些循环)之后,变量dimension2保存了for i in range(50)循环的最后一次迭代的值。 解决您遇到的问题包括:

for dimension2 in dimension1:
    for items in dimension2:
        # But I can't do more than 100 Threads at once.

您遇到问题的原因是尝试在不同的上下文中重用变量名称。但是,您在dimension2中构建的列表中没有存储变量名称的概念。