python - Python中的线程优先级

标签 python multithreading pthreads python-multithreading thread-priority

对于 music sampler ,我有两个主线程(使用 threading ):

  • 线程 #1 在需要时从磁盘中实时读取文件中的声音(例如:当我们在 MIDI 键盘上按下 C#3 时,我们需要尽快播放 C#3.wav!)如果此声音已加载到 RAM 中,则从 RAM ,
  • 线程 #2 将所有文件一个接一个地预加载到 RAM 中。

  • 线程#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()
    

    简而言之,我会处理thread2thread1 .如果 thread1很忙,然后我们暂停 thread2 .

    请注意,我添加了 loops只是为了杀死示例中的线程,但在实际情况下,将在关闭程序时调用 exit 函数。 (如果你的线程总是在后台运行)

    关于python - Python中的线程优先级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30824425/

    相关文章:

    python - python 中的 sigmoid 函数

    python - 使用 SimpleHTTPServer 禁用索引文件

    java - 当我尝试解析字符串时,我的应用程序崩溃了

    c++ - 在 C++ 中全局使用二维数组

    c - Pthread 的奇怪行为

    python - 数据类型传输/转换

    javascript - Ajax调用后,django不重定向给定的url?

    python - 在 Python 中实现实时信号处理——如何连续捕获音频?

    multithreading - 在线程停止时关闭窗口

    c - 从辅助线程获取主线程