1

Let's Imagine the code below:

import threading
from time import sleep


def short_task():
    sleep(5)
    print("short task")

def long_task():
    sleep(15)
    print("long task")

while True:
    st = threading.Thread(target=short_task())
    lt = threading.Thread(target=long_task())
    st.start()
    lt.start()
    st.join()
    lt.join()

I have two functions that each take different times to process, in my approach above the output is going to be as below:

short task
long task
short task
long task
short task
long task
short task
long task

but the desired output is:

short task
short task
short task
long task
short task
short task
short task
long task

what is the best way to achieve this? one maybe dirty way is to remove the main while loop and put a while loop in each thread.

2
  • Why would I need thread-locks?! these are two independent tasks that can be done separately! the order you can never guarantee, but it was just a simple example Commented Mar 4, 2021 at 6:01
  • You have to remove the () from the targets. Commented Mar 4, 2021 at 6:18

1 Answer 1

2

As you assumed in the question moving while loop to inside the threads will help to get results as you intended.

Also one more thing. You are calling the function when passing the target. You just need to pass the function name alone. eg: target=short_task

Also in your main while loop since you are waiting for thread to finish hence it makes sense that the output is coming alternatively. It is a logic mistake I believe.

Try below code should work as your expectation.

I have changed wait time of the short function to 4 instead of 5. So to make sure the order you desired is maintained.

import threading
from time import sleep


def short_task():
    while True:
        sleep(4)
        print("short task")


def long_task():
    while True:
        sleep(15)
        print("long task")


st = threading.Thread(target=short_task)
lt = threading.Thread(target=long_task)
st.start()
lt.start()
st.join()
lt.join()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.