24 Threading in python
'''
1. Threading is used to run multiple jobs concurrently(at the same time)
2. Using threading module we can achive threading in python.
target: the function to be executed by thread
args : the arguments to be passed to the target function
name : We can specify a name to the thread
join : Using join function we keep a thread to wait till ending the thread
'''
import threading
import time
def first_fun():
print(' \n first_thread started')
time.sleep(5)
print(' \n first_thread ended')
def second_fun(a,b):
print(' \n second_thread started')
time.sleep(5)
print(' \n second_thread ended')
# print(time.ctime())
# first_fun()
# second_fun(3,4)
# print(time.ctime())
ft = threading.Thread(target=first_fun)
st = threading.Thread(target=second_fun, args=('sriram','chowdary'))
print(time.ctime())
ft.start()
st.start()
st.join()
print(time.ctime())
### Thread count
'''
1. threading.activeCount(): Returns the number of total Python thread that are active.
'''
import threading
import time
def fun1():
time.sleep(1)
def fun2():
print(' \n Total threads count is :::::', threading.activeCount())
t1 = threading.Thread(target=fun1)
t2 = threading.Thread(target=fun2)
t1.start()
t2.start()
### get thread names
'''
1. threading.currentThread(): Returns the currentThread object
'''
import threading
import time
def fun1():
print(' \n Fun1 thread name is :::::', threading.currentThread().getName())
def fun2():
print(' \n Fun2 thread name is :::::', threading.currentThread().getName())
t1 = threading.Thread(target=fun1, name='ADD')
t2 = threading.Thread(target=fun2, name='SUB')
t1.start()
t2.start()
Comments
Post a Comment