Application python's threading module to open multi-threaded execution program, the program will shorten the running time, the following code demonstrates the multi-threaded applications
#不开启多线程演示 import time,threading def foo(n): print('foo%s'%n) time.sleep(1) def bar(n): print('bar%s'%n) time.sleep(2) begin = time.time() t1 = threading.Thread(target = foo,args = (1,)) t2 = threading.Thread(target = bar,args = (2,)) #t1.start() #t2.start() foo(1) bar(2) end = time.time() process_time = end - begin print('process time is:%s'%(str(process_time)))
The results without turning on the multithreaded above are as follows:
/home/guoming/python/day27/thread.py /usr/bin/python3.6
foo1
bar2
Process Time IS: 3.003460168838501
Process Exit code 0 Finished with
running took three seconds
#改写一下,开启两个线程 import time,threading def foo(n): print('foo%s'%n) time.sleep(1) def bar(n): print('bar%s'%n) time.sleep(2) begin = time.time() t1 = threading.Thread(target = foo,args = (1,)) t2 = threading.Thread(target = bar,args = (2,)) t1.start() t2.start() #foo(1) #bar(2) end = time.time() process_time = end - begin print('process time is:%s'%(str(process_time)))
After opening thread execution results are as follows:
/home/guoming/python/day27/thread.py /usr/bin/python3.6
foo1
bar2,
Process Time IS: .0003719329833984375
Process Finished with code 0 Exit
procedure in less than 1 second