Python 多重处理:在嵌套函数中使用

发布于 2025-01-10 13:00:44 字数 808 浏览 1 评论 0原文

我在网上找到了这段代码:

import multiprocessing
import time

def foo(n):
    for i in range(10000 * n):
        print(i)
        time.sleep(1)

if __name__ == '__main__':
    p = multiprocessing.Process(target=foo, name="Foo", args=(10,))
    p.start()
    time.sleep(10)
    p.terminate()
    p.join()

Is it is it possible to use that code inside a function?比如:

def test():
    def foo(n):
        for i in range(10000 * n):
            print(i)
            time.sleep(1)

    if __name__ == '__main__':
        p = multiprocessing.Process(target=foo, name="Foo", args=(10,))
        p.start()
        time.sleep(10)
        p.terminate()
        p.join()

当我尝试时总是出现错误。但我对 python 仍然很陌生,大多数时候不知道我真正在做什么。或者还有其他选择吗? (我使用的是 Windows,所以 SIGALRM 可能是没有选择的)

I found this code online:

import multiprocessing
import time

def foo(n):
    for i in range(10000 * n):
        print(i)
        time.sleep(1)

if __name__ == '__main__':
    p = multiprocessing.Process(target=foo, name="Foo", args=(10,))
    p.start()
    time.sleep(10)
    p.terminate()
    p.join()

Is it somehow possible to use that code inside a function? Something like:

def test():
    def foo(n):
        for i in range(10000 * n):
            print(i)
            time.sleep(1)

    if __name__ == '__main__':
        p = multiprocessing.Process(target=foo, name="Foo", args=(10,))
        p.start()
        time.sleep(10)
        p.terminate()
        p.join()

While I tried it there was always an error. But i'm still quite new to python and have most of the time no Idea what I'm really doing. Or is there maybe any alternative? (I'm using windows so SIGALRM is probably no alternative)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文