繁体   English   中英

使用并发的Python线程

[英]Python Threading With Concurrency

我在尝试学习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()

我试图得到一个输出,其中Thread-1和Thread-2同时启动。 IE打印

Thread-1 Stuff,Thread-2 Stuff,Thread-1 Stuff,Thread-2 Stuff,而不是

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

而是Thread-2仅在Thread-1之后启动。 我已经检查了在线示例,但我不明白我在机械上做错了什么。

要传递参数,您需要这样做:

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

您的代码在主线程上调用printWorker并以target = None(printWorker的返回值)启动两个线程。

暂无
暂无

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

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