Thread priority in Python

8.1k views Asked by At

For a music sampler, I have two main threads (using threading) :

  • Thread #1 reads sound from files from disk, in real-time, when needed (example: when we press a C#3 on the MIDI keyboard, we need to play C#3.wav as soon as possible!) or from RAM if this sound has been already loaded in RAM,

  • Thread #2 preloads all the files into RAM, one after another.

Thread #2 should be done in background, only during free time, but should not prevent Thread #1 to do its job quickly.

In short, Thread #1 should have much higher priority than Thread #2.

How to do that with threading or any other Python thread managament module? Or is it possible with pthread_setschedparam? How?

1

There are 1 answers

0
AudioBubble On

I'm not a big expert but I'll handle that problem like this:

#!/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()

In a few words, I'll handle thread2 with thread1. If thread1 is busy, then we pause thread2.

Note that I added loops just to kill the thread in the example, but in a real case the exit function would be called when closing the program. ( if your threads are always running in the background)