import threading
import time
import sys
def f():
'''
Processing you want to do asynchronously
This time, the number of seconds is displayed every second.
'''
i = 1
while True:
print(i)
i += 1
time.sleep(1)
th = threading.Thread(target=f,name="th",args=())
#Creation of thread th Method to be performed by target,The name of the thread in name,Specify arguments with args
th.setDaemon(True)
#Set th to daemon. When the main thread terminates, the daemon thread also terminates
th.start()
#Start thread
#Accepts character input, ends if a
#Since it is the main thread, when this ends, the daemon thread th also ends.
while True:
c = sys.stdin.read(1)
if c == 'a':
sys.exit()
I am creating a thread called th that displays the number of seconds every second. Exit when'a'is entered.
Recommended Posts