** “調用棧”與“線程”之間的不同**
調用棧:
def a():
print('a() starts')
b()
d()
print('a() returns')
def b():
print('b() starts')
c()
print('b() returns')
def c():
print('c() starts')
print('c() returns')
def d():
print('d() starts')
print('d() returns')
a()
線程代碼:
import threading
import time
def worker():
print(threading.current_thread().getName(), 'Starting')
time.sleep(0.2)
print(threading.current_thread().getName(), 'Exiting')
def my_service():
print(threading.current_thread().getName(), 'Starting')
time.sleep(0.3)
print(threading.current_thread().getName(), 'Exiting')
t = threading.Thread(name='my_service', target=my_service)
w = threading.Thread(name='worker', target=worker)
w2 = threading.Thread(target=worker) # use default name
w.start()
w2.start()
t.start()
線程運行結果:
worker Starting
Thread-1 Starting
my_service Starting
worker Exiting
Thread-1 Exiting
my_service Exiting
調用棧運行結果:
a() starts
b() starts
c() starts
c() returns
b() returns
d() starts
d() returns
a() returns
理解線程的並行過程以及各線程的運行時間,是學會利用線程的基礎;調用棧的運行過程,是python中函數調用的基本運行方式,方便更容易理解局部與全局作用域。