欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python并行调用同一个函数

程序员文章站 2024-01-25 20:28:16
...

要写一个函数,按照泊松分布的规律执行同一条命令,之前尝试threading和process都不行,后来参考https://www.cnpython.com/qa/423660,发现是创建进程的方式错误,参数应该写到args中,target不要写*(“canshu”)* mark一下

原错误代码:

proc = []
def requestEvent(interval, j, n):
    i = 0
    while i < n:
        print("Event Start : ",
              datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
        delay = interval[i + j * n]
        global proc
        p = Process(target = func())
        p.start()
        proc.append(p)
        print("Event End : ",
              datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
        time.sleep(delay)
        i += 1
     
def mymain():
    #.....code.....
    for p in proc:
        p.join()
    print('process end.')

修改后代码:

proc = []
def requestEvent(interval, j, n):
    i = 0
    while i < n:
        print("Event Start : ",
              datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
        delay = interval[i + j * n]
        global proc
        p = Process(target = func, args=("func",))
        p.start()
        proc.append(p)
        print("Event End : ",
              datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'))
        time.sleep(delay)
        i += 1
     
def mymain():
    #.....code.....
    for p in proc:
        p.join()
    print('process end.')
相关标签: python 多进程