如何同时运行2个进程?

huangapple go评论79阅读模式
英文:

How can I run 2 processes at the same time?

问题

我正在用Python制作一个闹钟需要启动2个进程第一个进程应该显示一个窗口第二个进程应该启动声音process1和process2尽管使用了多进程但是运行是交替的而不是同时的以下是代码

```python
# 导入时间模块
from datetime import datetime
# 导入界面模块
from tkinter import *
# 导入多进程模块
from multiprocessing import *
# 导入功能模块
from alarm_interface import window
from alarm_sound import alarm_sound

# 检查有效的闹钟时间的函数

def valid_alarm(val_al):
    if int(str(val_al[0:2])) > 23 or int(str(val_al[3:5])) > 59:
        return "无效的时间"
    else:
        return "通过"

# 主程序,询问用户闹钟的标题和时间

while True:
    print('闹钟的标题:', end=' ')
    name_of_alarm = input('')

    print('选择所需的时间。输入小时和分钟')

    print('小时:', end='')
    user_time_hour = int(input()[0:2])

    print('分钟:', end='')
    user_time_min = int(input()[0:2])

    user_time = "{:02d}:{:02d}".format(user_time_hour, user_time_min)

    # 检查有效时间
    if valid_alarm(user_time) == "无效的时间":
        print(valid_alarm(user_time))
    else:
        print("闹钟已设置为{:02d}:{:02d}".format(user_time_hour, user_time_min))
        break

# 主程序,比较当前时间和用户设置的时间
while True:

    current_time = str(datetime.now().time())[:5]

    if current_time == user_time:
        print(name_of_alarm)
        # 多进程
        process1 = Process(target=alarm_sound())
        process2 = Process(target=window())

        process2.start()
        process1.start()
        process2.join()
        process1.join()

我尝试使用线程库和多进程库来启动这两个进程。


<details>
<summary>英文:</summary>
I&#39;m making an alarm clock in python and I need to start 2 processes. The first one should display a window, and the second one should start the sound. process1 and process2, despite multiprocessing, run alternately, not simultaneously. Here is the code:

#import for time
from datetime import datetime
#import for interface
from tkinter import *
#import for parallel use
from multiprocessing import *
#import functions
from alarm_interface import window
from alarm_sound import alarm_sound

#Function that checks valid time

def valid_alarm(val_al):
if int(str(val_al[0:2]))>23 or int(str(val_al[3:5]))>59:
return "Invalid time"
else:
return "Pass"

#Main programm that asks user for title and time for alarm

while True:
print('Title of the alarm clock:',end=' ')
name_of_alarm=input('')

print(&#39;Select the desired time. Enter the hour and minute&#39;)
print(&#39;Hour:&#39;,end=&#39;&#39;)
user_time_hour=int(input()[0:2])
print(&#39;Minute:&#39;,end=&#39;&#39;)
user_time_min=int(input()[0:2])
user_time=&quot;{:02d}:{:02d}&quot;.format(user_time_hour,user_time_min)
#Checking valid time
if valid_alarm(user_time)==&quot;Invalid time&quot;:
print(valid_alarm(user_time))
else:
print((&quot;The alarm clock is set to {:02d}:{:02d}&quot;).format(user_time_hour,user_time_min))
break

#Main programm that compares current time and user time
while True:

current_time=str(datetime.now().time())[:5]
if current_time==user_time:
print(name_of_alarm)
#multiprocessing
process1=Process(target=alarm_sound())
process2=Process(target=window())
process2.start()
process1.start()
process2.join()
process1.join()

I tried to start these 2 processes with thread library and multiprocessing library
</details>
# 答案1
**得分**: 1
有关代码存在一些问题:
1. 缺少[主模块的安全导入](https://docs.python.org/3.8/library/multiprocessing.html#the-spawn-and-forkserver-start-methods)
确保主模块可以被新的 Python 解释器安全地导入,而不会引起意外的副作用(比如启动一个新进程)。
例如,使用 spawn 或 forkserver 启动方法运行以下模块会导致 RuntimeError:
```python
from multiprocessing import Process
def foo():
print('hello')
p = Process(target=foo)
p.start()

相反,应该通过使用 if __name__ == '__main__': 来保护程序的“入口点”,如下所示:

from multiprocessing import Process, freeze_support, set_start_method

def foo():
    print('hello')

if __name__ == '__main__':
    freeze_support()
    set_start_method('spawn')
    p = Process(target=foo)
    p.start()
  1. Process 初始化时调用了函数:
Process(target=alarm_sound())

应该改为:

Process(target=alarm_sound)

代码示例:

def get_user_time():
    while True:
        print('Title of the alarm clock:', end=' ')
        name_of_alarm = input('')
        # ...
        if valid_alarm(user_time) == "Invalid time":
            print(valid_alarm(user_time))
        else:
            print("The alarm clock is set to {:02d}:{:02d}".format(user_time_hour, user_time_min))
            return user_time, name_of_alarm

if __name__ == '__main__':
    user_time, name_of_alarm = get_user_time()
    while True:
        current_time = str(datetime.now().time())[:5]
        if current_time == user_time:
            print(name_of_alarm)
            process1 = Process(target=alarm_sound)
            process2 = Process(target=window)
            process2.start()
            process1.start()
            process2.join()
            process1.join()
英文:

There are several issues with the code:

  1. Missing Safe importing of main module

> Make sure that the main module can be safely imported by a new Python
> interpreter without causing unintended side effects (such a starting a
> new process).
>
> For example, using the spawn or forkserver start method running the
> following module would fail with a RuntimeError:
>
> from multiprocessing import Process
>
> def foo():
> print('hello')
>
> p = Process(target=foo)
> p.start()
>
> Instead one should protect the “entry point” of the program by using
> if __name__ == &#39;__main__&#39;: as follows:
>
> from multiprocessing import Process, freeze_support, set_start_method
>
> def foo():
> print('hello')
>
> if name == 'main':
> freeze_support()
> set_start_method('spawn')
> p = Process(target=foo)
> p.start()

  1. You are invoking the functions on Process initialization

    Process(target=alarm_sound())
    

    should be

    Process(target=alarm_sound)
    

Code sample:

def get_user_time():
while True:
print(&#39;Title of the alarm clock:&#39;, end=&#39; &#39;)
name_of_alarm = input(&#39;&#39;)
...
if valid_alarm(user_time) == &quot;Invalid time&quot;:
print(valid_alarm(user_time))
else:
print((&quot;The alarm clock is set to {:02d}:{:02d}&quot;).format(user_time_hour, user_time_min))
return user_time, name_of_alarm
if __name__ == &#39;__main__&#39;:
user_time, name_of_alarm = get_user_time()
while True:
current_time = str(datetime.now().time())[:5]
if current_time == user_time:
print(name_of_alarm)
process1 = Process(target=alarm_sound)
process2 = Process(target=window)
process2.start()
process1.start()
process2.join()
process1.join()

huangapple
  • 本文由 发表于 2023年7月23日 18:47:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76747823.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定