1

i want to ask , i try with my coding but it still not working, i want to execute 2 loop with delay and print each word with delay.

here my coding

import threading,time

def func_name1():
fruits = ["apple", "banana", "cherry"]
for i in fruits:
    time.sleep(2)
    print(i)

def func_name2():
fruits2 = ["1", "2", "3"]
for i in fruits2:
    time.sleep(2)
    print(i)

f1 = threading.Thread(target=func_name1)
f2 = threading.Thread(target=func_name2)
f1.start()
time.sleep(2)
f2.start()

output like this

apple
1
banana
2
cherry
3

i want scenario like this

enter image description here

6
  • Please edit your post to properly indent your python code Commented Dec 2, 2022 at 11:03
  • Also please include the actual output. In what way doesn't it work? Commented Dec 2, 2022 at 11:05
  • the output is like that, but i want when execute loop 1 print : apple , then delay , after that execute second loop print : 1 , {delay} , and back to execute first loop. Commented Dec 2, 2022 at 11:08
  • Output is like what? You need to edit your post to include the current output Commented Dec 2, 2022 at 11:09
  • 1
    @AchmadRivaldi FWIW, You could do that with one function instead of two. Commented Dec 2, 2022 at 11:11

1 Answer 1

1

Try this.

I have updated my code Now it matches your scenario. The whole Script takes approximatly 25.03 seconds.

def func_name1():
    fruits = ["apple", "banana", "cherry"]
    a = 0
    for i in fruits:
        a += 1
        print(i)
        if a == len(fruits):
            return
        time.sleep(10)

def func_name2():
    fruits2 = ["1", "2", "3"]
    a = 0
    for i in fruits2:
        a +=1
        print(i)
        if a==len(fruits2):
            return
        time.sleep(10)

f1 = threading.Thread(target=func_name1)
f2 = threading.Thread(target=func_name2)
f1.start()
time.sleep(5)
f2.start()
apple
1
banana
2
cherry
3

To check the whole execution time. Use this code.


import threading,time

t = time.time()

def func_name1():
    fruits = ["apple", "banana", "cherry"]
    a = 0
    for i in fruits:
        a += 1
        print(i)
        if a == len(fruits):
            return
        time.sleep(10)

def func_name2():
    fruits2 = ["1", "2", "3"]
    a = 0
    for i in fruits2:
        a +=1
        print(i)
        if a==len(fruits2):
            return
        time.sleep(10)

f1 = threading.Thread(target=func_name1)
f2 = threading.Thread(target=func_name2)
f1.start()
time.sleep(5)
f2.start()

f2.join()

print(time.time() - t)

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.