Python-在for循环中限制线程

时间:2019-03-11 18:50:21

标签: python python-3.x multithreading

我正在尝试将此循环限制为4个并发作业:

def testSSH(host, user, password, port):
s = pxssh.pxssh()
try:
    if not s.login (host, username=user, password=password, port=port):
        print(password)
        return False
    else:
        print(password)
        return True
except:
    print(password)
    return False




passes = "r", "1234", "12345", "123456!", "1234567", "a", "b", "e", "s", "A", "d", "66"

jobs = []
for passw in passes:
    thread = threading.Thread(target=testSSH, args=("localhost", "myuser", passw, "22",))
    jobs.append(thread)

for j in jobs:
        print(threading.active_count())
        j.start()

for j in jobs:
        j.join()

代码运行正常。但是,我似乎无法限制并发作业。 threading.active_count()始终是pass的值。 有小费吗?我尝试过this question,但做得很少 谢谢!

1 个答案:

答案 0 :(得分:0)

好的,我自己发现了一些东西

threads = 0
def testSSH(host, user, password, port):
s = pxssh.pxssh()
try:
    if not s.login (host, username=user, password=password, port=port):
        print(password)
        return False
    else:
        print(password)
        return True
except:
    print(password)
    return False




passes = "r", "1234", "12345", "123456!", "1234567", "a", "b", "e", "s", "A", "d", "66"

jobs = []
for passw in passes:
    thread = threading.Thread(target=testSSH, args=("localhost", "myuser", passw, "22",))
    jobs.append(thread)

for j in jobs:
    threads = threading.active_count()
    while threads > 4:
    time.sleep(0.05)
    threads = threading.active_count()
        j.start()

for j in jobs:
        j.join()

希望这可以帮助某人...