我想完全同时执行以下两个功能。

from multiprocessing import Process
import os
import datetime

def func_1(title):
    now = datetime.datetime.now()
    print "hello, world"
    print "Current second: %d" % now.second
    print "Current microsecond: %d" % now.microsecond

def func_2(name):
    func_1('function func_2')
    now = datetime.datetime.now()
    print "Bye, world"
    print "Current second: %d" % now.second
    print "Current microsecond: %d" % now.microsecond

if __name__ == '__main__':
    p = Process(target=func_2, args=('bob',))
    p.start()
    p.join()

而且我得到微秒的不同。有什么办法可以在完全相同的时间执行这两个操作?任何帮助,将不胜感激。

最佳答案

在计算机上编写了以下内容,此代码一致地打印出相同的时间戳记:

#! /usr/bin/env python3
from multiprocessing import Barrier, Lock, Process
from time import time
from datetime import datetime

def main():
    synchronizer = Barrier(2)
    serializer = Lock()
    Process(target=test, args=(synchronizer, serializer)).start()
    Process(target=test, args=(synchronizer, serializer)).start()

def test(synchronizer, serializer):
    synchronizer.wait()
    now = time()
    with serializer:
        print(datetime.fromtimestamp(now))

if __name__ == '__main__':
    main()

关于python - Python的多重处理: execute two functions at the exact same time,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13475113/

10-11 21:23