Git Product home page Git Product logo

Comments (2)

tmKnight01 avatar tmKnight01 commented on June 2, 2024

我昨天在mac中也遇到了这个error 看来还真的会区分系统

from python-100-days.

MCbrandon2003 avatar MCbrandon2003 commented on June 2, 2024

macOS 从 Python 3.8 开始默认使用 'spawn' 方法以避免与 Objective-C 运行时的冲突。

以下是修改后的代码,它将自动检测操作系统并相应地设置适当的进程启动方法。此外,我还添加了一些错误处理以确保主进程等待子进程完成,并适当地关闭队列。

import os
from multiprocessing import Process, Queue, set_start_method, get_start_method
from time import sleep


def sub_task(string, q):
    a = q.get()
    sleep(0.01)
    while a < 10:
        if q.empty():
            q.put(a + 1)
            sleep(0.01)
            print(string, end='', flush=True)
            a = q.get()
    if q.empty():
        q.put(a + 1)
        sleep(0.1)


def main():
    set_start_method("spawn")

    q = Queue()
    q.put(0)
    p1 = Process(target=sub_task, args=('Ping', q))
    p2 = Process(target=sub_task, args=('Pong', q))

    # 启动进程
    p1.start()
    p2.start()

    # 等待进程完成
    p1.join()
    p2.join()

    print("\nProcesses completed.")


if __name__ == '__main__':
    main()

from python-100-days.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.