简体   繁体   中英

Python Threading With Concurrency

I wrote the following code while trying to learn threading in python.

    import threading
    import time

    def printWorker(x,y):
        t = time.time()
        while time.time() - t < 10:
            print "Name:%s  Time:%s" %(y,str(time.time() - t))
            time.sleep(x)

    t1 = threading.Thread(target = printWorker(2,'Thread-1'))
    t2 = threading.Thread(target = printWorker(3,'Thread-2'))

    t1.start()
    t2.start()

Im trying to get an output where both Thread-1 and Thread-2 start at same time. IE Print

Thread-1 Stuff, Thread-2 Stuff, Thread-1 Stuff, Thread-2 Stuff, instead of

Thread-1 Stuff, Thread-1 Stuff, Thread-1 Stuff, Thread-1 Stuff, Thread-2 Stuff, Thread-2 Stuff, Thread-2 Stuff, Thread-2 Stuff

Instead Thread-2 Only starts after Thread-1. I've checked online examples but I don't understand what I'm doing wrong mechanically.

To pass arguments you need to do this:

t1 = threading.Thread(target=printWorker, args=(2, 'Thread-1'))
t2 = threading.Thread(target=printWorker, args=(3, 'Thread-2'))

Your code is invoking printWorker on the main thread and starting two threads with target=None (the return value of printWorker).

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