简体   繁体   中英

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:

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

    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.

This should continue till loop A runs 99 times and loop B runs only once.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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