在python中并行执行'N'函数



我知道这个问题已经被问了很多次,但我找不到对我有帮助的答案。我的问题是,我们能否在python中并行执行两个函数,其中每个函数都有一个for循环,运行并打印一些值。例如,我有两个函数a((和b((,其中a((打印数字1..n(比如n=3(,b((打印当前时间的数字11.n(比方n=13(。我希望输出如下:

function a :1 2018-11-02 15:32:58
function b :11 2018-11-02 15:32:58
function a :2 2018-11-02 15:32:59
function b :12 2018-11-02 15:32:59

但它目前打印以下内容:

function a :1 2018-11-02 15:32:58
function a :2 2018-11-02 15:32:59
function b :11 2018-11-02 15:33:00
function b :12 2018-11-02 15:33:01

代码:

import time
from threading import Thread
import datetime
def a():
for i in range(1,3):
print 'function a :'+str(i) + ' ' + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(1)
def b():
for i in range(11,13):
print 'function b :'+str(i) + ' ' + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time.sleep(1)
if __name__=="__main__":
t1=Thread(target=a())
t2=Thread(target=b())
t1.start()
t2.start()

这里的问题是将target作为a()而不是a(注意括号(。这意味着,您将调用函数a,然后将其结果作为target传递给Thread。这不是你想要的——你希望target是函数a本身。因此,在实例化Thread时只需删除括号,如下所示:

if __name__=="__main__":
t1=Thread(target=a)
t2=Thread(target=b)
t1.start()
t2.start()

最新更新