优化程序,将这段程序放到子线程里。def rotate(self): count = 0 self._sem.release() while self._running: v = self._dgl.qpin(ROT) if len(v) > 0: count = count + sum(v) if count > self._inspect_step: self._sem.release() count = count % self._inspect_step
时间: 2024-01-30 15:02:13 浏览: 89
可以使用Python内置的`threading`模块来将程序放到子线程中运行。具体实现如下:
```python
import threading
class MyThread(threading.Thread):
def __init__(self, rotate_func):
threading.Thread.__init__(self)
self.rotate_func = rotate_func
def run(self):
self.rotate_func()
class MyClass:
def __init__(self):
self._running = True
self._sem = threading.Semaphore(0)
def rotate(self):
count = 0
self._sem.release()
while self._running:
v = self._dgl.qpin(ROT)
if len(v) > 0:
count = count + sum(v)
if count > self._inspect_step:
self._sem.release()
count = count % self._inspect_step
my_class = MyClass()
thread = MyThread(my_class.rotate)
thread.start()
```
这样,`rotate`方法就会在一个独立的线程中运行,不会阻塞主线程。当需要停止`rotate`方法时,只需要将`my_class._running`设置为`False`即可。
阅读全文