Home > Software design >  Is it possible to wait for Try Else Block execution with threading?
Is it possible to wait for Try Else Block execution with threading?

Time:03-04

In the below code attached is there any way I can wait for else block print statement to get executed only after threading is done currently as the function gg is threaded I am getting output

HelloNothing went wrong

Hello

Expected output

Hello
Hello
Nothing went wrong

Current code

import threading
import time 


def gg():
    print("Hello")
    time.sleep(5)
    print("Hello")

try:
    threading.Thread(target=gg).start()
except:
    print("Something went wrong")
else:
    print("Nothing went wrong")

CodePudding user response:

You can use Join method

import threading
import time


def gg():
    print("Hello")
    time.sleep(5)
    print("Hello")


t1 = threading.Thread(target=gg)
try:
    t1.start()
    t1.join()
except:
    print("Something went wrong")
else:
    print("Nothing went wrong")
  • Related