Home > Net >  thread priority in Python time frequency
thread priority in Python time frequency

Time:12-18

I am using multiple threads in python.

One thread will run exactly after 1 minute frequency. Another will run after every 2 minutes. one more will run after 10 minutes.

first one and second one will suppose to start together every 2 minutes. But I want one of them to run first.

similarly at every 10 minutes all of them will run simultaneously together. But I am looking for 1th one to start first , 2nd one to start second and 3rd one to start last at the frequency of every 10 minutes.

so is it possible to have thread priority in case of multiple threads ?

CodePudding user response:

Threads aren't really supposed to give you any guarantees about the order of execution. You have a couple of options to define it yourself:

Describe the sequence in the main thread

If you currently have something like

def target1():
    target1_start()
    target1_body()

def target2():
    target2_start()
    target2_body()

def main():
    thread1 = Thread(target=target1)
    thread2 = Thread(target=target2)

Change it to

def main():
    target1_start()
    thread1 = Thread(target=target1_body)
    target2_start()
    thread2 = Thread(target=target2_body)

Hack with global variables

def target1():
    nonlocal thread1_started
    target1_start()
    thread1_started = True
    target1_body()

def target2():
    nonlocal thread1_started
    while not thread1_started:
        time.sleep(0.1)
    target2_start()
    target2_body()

def main():
    thread1_started = False
    thread1 = Thread(target=target1)
    thread2 = Thread(target=target2)

But this is very ugly, I suggest using the first option if possible

CodePudding user response:

no, there is no thread priority in python, you can however create mutiple threads and have them time.sleep(), and use a timer event to time your code execution on the other threads.

# this makes program execute after an interval
from time import time, sleep
def work_once(time_seconds):
    sleep(time_seconds) # run after time_seconds seconds.
    # thing to run after time_seconds.
# this makes program sleep in intervals
from time import time, sleep

def work_interval(time_seconds):
    while True:
        sleep(time_seconds - time() % time_seconds) # run every time_seconds seconds.
        # thing to run every time_seconds.

and have your main thread pass in the time as argument when instantiating your thread.

from threading import Thread
worker = Thread(work_interval,args=(2,))
worker.start()
  • Related