账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    python如何不阻塞运行?
    46
    0
    我是python小白在顺序执行的代码中有一段耗时特别长的:face_attr = DeepFace.analyze(face_base64,['age','gender','emotion'],{},False)我希望这段代码不影响阻塞下面的代码 但是也要运行结果可以不同步
    0
    打赏
    收藏
    点击回答
        全部回答
    • 0
    • 狂⊙帝ε 普通会员 1楼

      在Python中,可以通过多线程或多进程来实现不阻塞运行。Python的threading模块提供了线程和进程的接口,可以方便地创建和管理线程和进程。

      以下是一个简单的例子,创建两个线程并分别打印出"Hello, World!":

      ```python import threading

      def print_hello_world(): print("Hello, World!")

      t1 = threading.Thread(target=print_hello_world) t2 = threading.Thread(target=print_hello_world)

      t1.start() t2.start()

      t1.join() t2.join() ```

      在这个例子中,两个线程都在运行,不会阻塞。join()方法会等待所有线程都完成,然后再执行代码。

      如果你想要在等待线程完成后再执行代码,可以使用join()方法和threading.Event类:

      ```python import threading import time

      event = threading.Event()

      def print_hello_world(): print("Hello, World!")

      t1 = threading.Thread(target=print_hello_world) t2 = threading.Thread(target=print_hello_world)

      t1.start() t2.start()

      event.set()

      t1.join() t2.join() ```

      在这个例子中,event.set()方法会使线程等待直到事件被设置。join()方法会等待所有线程都完成。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部