Threads
Threads
import threading
def new():
for x in range(6):
print("Child Thread Here!!")
t1=Thread(target=new)
t1.start()
t1.join()
print("Main Thread Here!!")
2. import time
import threading
def calc_square(number):
print("Calculate square numbers: ")
for i in numbers:
time.sleep(0.2) #artificial time-delay
print('square: ', str(n*n))
def calc_cube(number):
print("Calculate cube numbers: ")
for i in numbers:
time.sleep(0.2)
print('cube: ', str(n*n*n))
arr = [2,3,8,9]
t = time.time()
t1 = threading.Thread(target = cal_square,args=(arr,))
t2 = threading.Thread(target = cal_cube,args=(arr,))
# creating two threads here t1 & t2
t1.start()
t2.start()
# starting threads here parallelly by usign start function.
t1.join() # this join() will wait until the cal_square() function is finised.
t2.join() # this join() will wait unit the cal_cube() function is finised.
print("Successed!")
3. import _thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print ("%s: %s" % ( threadName, time.ctime(time.time()) ))
# Create two threads as follows
try:
_thread.start_new_thread( print_time, ("Thread-1", 2, ) )
_thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print ("Error: unable to start thread")
while 1:
pass
4.
import threading
import time
threadLock = threading.Lock()
threads = []
4.timer program
import threading
import time
def hello():
print("hello, Timer")
if __name__ == '__main__':
t = threading.Timer(3.0, hello)
t.start()
After 3 seconds, "hello, Timer" will be printed.
#Take code from textbook and modify