gpt4 book ai didi

python - Python中的线程优先级

转载 作者:行者123 更新时间:2023-12-03 12:47:58 24 4
gpt4 key购买 nike

对于 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/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com