Python中的多处理:完全同时执行两个函数 [英] Multiprocessing in Python: execute two functions at the exact same time

查看:3190
本文介绍了Python中的多处理:完全同时执行两个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to execute the following two functions at exactly the same time.

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()

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

And I am getting a difference in microseconds. Is there any way to execute both at the exact same time? Any help would be appreciated.

推荐答案

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

On the computer the following was written on, this code consistently prints out the same timestamps:

#! /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中的多处理:完全同时执行两个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆