[英]Python Threading With Concurrency
I wrote the following code while trying to learn threading in python. 我在尝试学习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. 我试图得到一个输出,其中Thread-1和Thread-2同时启动。 IE Print IE打印
Thread-1 Stuff, Thread-2 Stuff, Thread-1 Stuff, Thread-2 Stuff, instead of 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-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. 而是Thread-2仅在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). 您的代码在主线程上调用printWorker并以target = None(printWorker的返回值)启动两个线程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.