对于 music sampler ,我有两个主线程(使用 threading
):
线程#2 应该在后台完成,仅在空闲时间完成,但不应阻止线程#1 快速完成其工作。
简而言之,线程#1 应该比线程#2 具有更高的优先级。
如何使用
threading
或任何其他 Python 线程管理模块? 或者 pthread_setschedparam
有可能吗? ?如何?
最佳答案
我不是一个大专家,但我会像这样处理这个问题:
#!/usr/bin/python2.7
# coding: utf-8
import threading, time
class Foo:
def __init__(self):
self.allow_thread1=True
self.allow_thread2=True
self.important_task=False
threading.Thread(target=self.thread1).start()
threading.Thread(target=self.thread2).start()
def thread1(self):
loops=0
while self.allow_thread1:
for i in range(10):
print ' thread1'
time.sleep(0.5)
self.important_task=True
for i in range(10):
print 'thread1 important task'
time.sleep(0.5)
self.important_task=False
loops+=1
if loops >= 2:
self.exit()
time.sleep(0.5)
def thread2(self):
while self.allow_thread2:
if not self.important_task:
print ' thread2'
time.sleep(0.5)
def exit(self):
self.allow_thread2=False
self.allow_thread1=False
print 'Bye bye'
exit()
if __name__ == '__main__':
Foo()
简而言之,我会处理
thread2
与 thread1
.如果 thread1
很忙,然后我们暂停 thread2
.请注意,我添加了
loops
只是为了杀死示例中的线程,但在实际情况下,将在关闭程序时调用 exit 函数。 (如果你的线程总是在后台运行)
关于python - Python中的线程优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30824425/