首页 > 解决方案 > 仅当第一个函数首先使用 Multiprocessing 运行时才一起运行两个函数

问题描述

我想让 2 个函数一起运行,但是首先应该运行 func1() 并且 func1() 应该调用 func2() 然后两个函数应该同时运行,直到满足所有条件。这是虚拟代码

x=1
def func1():
    global x
    while x>0:
       a=input()
       do something
       func2()              #calling func2() only once


def func2():
    global x
    while 1:
       if x==5:
          x=0              #x become 0 so now while loop for func1 should end
          break
      x+=1

这是我尝试使用多处理运行的代码。

import datetime
from time import sleep
from threading import *
from multiprocessing import Process
import sys

bot_reply_time = 0
x = 1
def func1():
    y = 0
    global bot_reply_time
    while x > 0:
        a = input("Q>")                          #EOF error here when reading a line
        print("Bot replay: Hi")
        c = datetime.datetime.now()
        bot_reply_time = (c.hour * 60 * 60) + (c.minute * 60) + c.second
        if y == 0:
            y += 1
            p2 = Process(target=func2)          #calling func2 only once
            p2.start()
def func2():
    global x
    global bot_reply_time
    while True:
        last_bot_reply_time = bot_reply_time
        c = datetime.datetime.now()
        current_time = (c.hour * 60 * 60) + (c.minute * 60) + c.second
        if (bot_reply_time + 10 == current_time and bot_reply_time == last_bot_reply_time):
            x = 0                           #x become 0 so now while loop for func1 should end
            print("session expired")
            break


if __name__=='__main__':
    p1 = Process(target = func1)
    p1.start()

但是,我收到错误为“读取一行时 EOF”。如果我删除“input()”,我不会收到错误

标签: pythonpython-3.x

解决方案


这里我有一个小例子,如何使用信号在函数中设置超时:

import signal
from contextlib import contextmanager


@contextmanager
def timeout(time):
    # Register a function to raise a TimeoutError on the signal.
    signal.signal(signal.SIGALRM, raise_timeout)
    # Schedule the signal to be sent after ``time``.
    signal.alarm(time)

    try:
        yield
    except TimeoutError:
        pass
    finally:
        # Unregister the signal so it won't be triggered
        # if the timeout is not reached.
        signal.signal(signal.SIGALRM, signal.SIG_IGN)


def raise_timeout(signum, frame):
    raise TimeoutError


def my_func():
    # Add a timeout block.
    with timeout(1):
        print('entering block')
        import time
        time.sleep(10)
        print('This should never get printed because the line before timed out')

我希望它有所帮助,但如果你想要一种更简单的方式,只需使用func-timeoutpython 模块。

https://pypi.org/project/func-timeout/

推荐阅读