简体   繁体   English

Python:如何同时运行两个循环并将迭代参数传递给它们?

[英]Python: How to run two loops simultaneously and pass iterative arguments to them?

I want to run two loops using multi-threading. 我想使用多线程运行两个循环。 The iteration for both the loops should give a combined sum of 100. For Example: 两个循环的迭代总和应为100。例如:

def loopA():
   for i in xrange(1,100):
       Do A

def loopB():
   for j in xrange(1,100):
       Do B

Now the sum i+j at any given time should be 100 现在,任何给定时间的i + j之和应为100

    threadA = Thread(target = loopA)
    threadB = Thread(target = loobB)      
    threadA.run()
    threadB.run()

So when loop A runs once, loop B should run 99 times simultaneously.(i+j=100) loop A runs twice, loop B should run 98 times simultaneously. 因此,当循环A运行一次时,循环B应同时运行99次。(i + j = 100)循环A运行两次,则循环B应同时运行98次。

This should continue till loop A runs 99 times and loop B runs only once. 这应该持续到循环A运行99次并且循环B仅运行一次。

Let's take threading out of the picture to begin with, because it sounds like even you aren't sure exactly what you're trying to do. 让我们先从图片中抽出线索,因为听起来甚至不确定自己到底想做什么。 Let's also stop naming them confusingly, and instead call a rose a rose. 让我们也不要混淆地命名它们,而是称玫瑰为玫瑰。

def encrypt(s, n):
    """Runs string s through n rounds of encryption"""
    for _ in range(n):
        s = some_encryption_method(s)
    return s

def decrypt(s, n):
    """Runs string s through n rounds of decryption"""
    for _ in range(n):
        s = some_decryption_method(s)
    return s

From here it's pretty clear how to proceed. 从这里很清楚如何进行。

for encrypt_rounds in range(101):  # 0 -> 100 inclusive
    decrypt_rounds = 100 - encrypt_rounds
    encrypted_s = encrypt(some_string, encrypt_rounds)
    decrypted_s = decrypt(some_string, decrypt_rounds)

Why do you want to do this in a thread? 为什么要在线程中执行此操作? It's not clear what you're gaining from using threading, but it is very clear that losing synchronicity is a problem. 不清楚您从使用线程获得了什么,但是清楚失去同步性是一个问题。 Let's keep it simple, then, and drop threading altogether until we know we need it! 让我们保持简单,然后完全放弃线程,直到我们知道我们需要它为止!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM