python threading library Perform a new activity

20 Views Asked by At

please attention to this simple program:

from time import sleep

from threading import Thread

def fun1():

sleep(10)

thread1 = Thread(target = fun1)

thread1.start()

#sign

sleep(100)

print("hello")

how can I stop execution of the codes below the #sign when thread1 finished.

thank you for your helping

1

There are 1 best solutions below

0
Lolser9 On

Here's one solution. Instead of sleeping for 100 seconds, which would cause the main program to be inactive during that entire period, you can opt for a one-second sleep while monitoring the elapsed time using the count variable. Doing so eliminates the need to wait for the program to conclude for 100 seconds after func1 completes. Upon the termination of the thread, the program will end as the condition thread1.is_alive() will be evaluated as false

from time import sleep
from threading import Thread

def fun1():
    sleep(10)
    print("Fun1 done")


if __name__ == "__main__":
    thread1 = Thread(target=fun1)
    thread1.start()

    count = 0
    while thread1.is_alive():
        sleep(1)
        count += 1
        if count >= 100:  # Wait for 100 seconds
            print("hello")  # Sign content
            count = 0

    thread1.join()