python - Python 中的多处理 : execute two functions at the exact same time

标签 python parallel-processing multiprocessing

我想同时执行以下两个函数。

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/

相关文章:

c - 使用 OpenMP 和 block 方法加速矩阵乘法 : Can I Do Better?

python - 子进程未按预期返回数据

c++ - openMP - 需要原子或减少条款

python - 将字符串列表转换为函数调用

r - macOS 和 CentOS 上的并行 Caret 与 doSNOW 集群

python - hashlib 与 Python 中的 crypt.crypt() 对比。为什么会有不同的结果?

java - 使用 spring async 进行并行调用后连接结果

python - 与外部程序的多重处理 - 执行速度

python - 在操作代码中间定义函数在 Python 中是不好的做法吗?

python - wsadmin 脚本中未处理的异常后的误导性错误消息