Python多线程 - 关闭Blender中的线程

0 投票
1 回答
3646 浏览
提问于 2025-04-17 15:25

我遇到一个小问题,关于在Blender游戏引擎中运行的多线程Python脚本。这个脚本运行得还不错,但当我停止游戏时,它会出现一些异常,有时候还会崩溃。

from bge import logic
import time
from threading import Thread

def init():

    if not hasattr(logic, 'init'):
        logic.init = 0
        logic.thread = new()
        logic.thread.start()

    logic.thread.restart()

class new(Thread):
    def __init__(self):
        self.Thread = Thread
        self.Thread.__init__(self)
    def run(self):
        number = 0
        while 1:
            number += 1
            print(number)
            try:
                main()
                time.sleep(0.1)
            except:
                break

    def restart(self):
        self.Thread.__init__(self)

def main(): #this part isn't important now ...
    cam = bge.logic.getCurrentScene().active_camera
    obj = bge.logic.getCurrentController().owner
    obj.worldPosition.x = cam.worldPosition.x
    obj.worldPosition.y = cam.worldPosition.y

控制台显示:

Unhandled exception in thread started by <bound method new._bootstrap of <new(Th
read-80, initial)>>
Traceback (most recent call last):
  File "C:\Program Files (x86)\Blender Foundation\Blender\2.64\python\lib\thread
ing.py", line 709, in _bootstrap
    self._bootstrap_inner()
  File "C:\Program Files (x86)\Blender Foundation\Blender\2.64\python\lib\thread
ing.py", line 784, in _bootstrap_inner
    with _active_limbo_lock:
AttributeError: __exit__

如果有人能帮我找出问题所在,我会非常感激。谢谢!

1 个回答

2

这是一个关于在Blender中使用Python脚本的众所周知的限制。

问题在于,当Blender关闭时,它会先结束Python的运行,而你的线程可能还在运行。你可以尝试做的是,想办法注册一个事件,告诉你的线程Blender(或者你的游戏)要退出了,然后在主线程中使用join来等待这个线程结束。

撰写回答